<?php
class Project extends Controller
{

    //Global variable  
    public $outputData; //Holds the output data for each view
    public $loggedInUser;

    /**
     * Constructor
     *
     * Loads language files and models needed for this controller
     */
    function Project()
    {
        parent::Controller();

        //Get Config Details From Db
        $this->config->db_config_fetch();

        //Manage site Status 
        if ($this->config->item('site_status') == 1)
            redirect('offline');


        //Load the helper file reviews
        $this->load->helper('reviews');
        $this->load->helper('file');
        $this->load->helper('alert');

        //language file
        $this->lang->load('enduser/common', $this->config->item('language_code'));
        $this->lang->load('enduser/project', $this->config->item('language_code'));
        $this->lang->load('enduser/createProject', $this->config->item('language_code'));


        //Debug Tool
        // $this->output->enable_profiler=true;		

        //Load Models Common to all the functions in this controller
        $this->load->model('common_model');
        $this->load->model('skills_model');
        $this->load->model('user_model');
        $this->load->model('transaction_model');
        $this->load->model('settings_model');
        $this->load->model('file_model');
        $this->load->model('email_model');
        $this->load->model('messages_model');
        $this->load->model('certificate_model');
        //Page Title and Meta Tags
        $this->outputData = $this->common_model->getPageTitleAndMetaData();

        //Get Top programmers
        $topProgrammers = $this->common_model->getPageTitleAndMetaData();

        //Get Logged In user
        $this->loggedInUser = $this->common_model->getLoggedInUser();
        $this->outputData['loggedInUser'] = $this->loggedInUser;


        //Get Footer content
        $this->outputData['pages'] = $this->common_model->getPages();

        //Get Latest Projects
        $limit_latest = $this->config->item('latest_projects_limit');
        $limit3 = array($limit_latest);
        $this->outputData['latestProjects'] = $this->skills_model->getLatestProjects($limit3);

        //Get draft Projects
        if (isset($this->loggedInUser->id)) {
            $flag = 0;
            $condition = array('draftprojects.creator_id' => $this->loggedInUser->id, 'draftprojects.flag' => $flag);
            $this->outputData['draftProjects'] = $this->skills_model->getDraft($condition);

            $conditions = array('user_list.creator_id' => $this->loggedInUser->id, 'user_list.user_role' => '1');
            $this->outputData['favouriteUsers'] = $this->user_model->getFavourite($conditions);
            $this->outputData['project_period'] = $this->config->item('project_period');
        }

        //Post the maximum size of memory limit
        $maximum = $this->config->item('upload_limit');
        $this->outputData['maximum_size'] = $maximum;
        if ($this->loggedInUser) {
            //Conditions
            $conditions = array('files.user_id' => $this->loggedInUser->id);
            $this->outputData['fileInfo'] = $this->file_model->getFile($conditions);
        }

        //Get Certificate User 

        if ($this->loggedInUser) {

            $condition = array('subscriptionuser.username' => $this->loggedInUser->id);

            $userlists = $this->certificate_model->getCertificateUser($condition);

            if ($userlists->num_rows() > 0) {
                // get the validity
                $validdate = $userlists->row();
                $end_date = $validdate->valid;
                $created_date = $validdate->created;
                $valid_date = date('d/m/Y', $created_date);

                $next = $created_date + ($end_date * 24 * 60 * 60);
                $next_day = date('d/m/Y', $next) . "\n";

                if (time() <= $next) {
                    $paymentSettings = $this->settings_model->getSiteSettings();

                    $this->outputData['feature_project'] = $paymentSettings['FEATURED_PROJECT_AMOUNT_CM'];
                    $this->outputData['urgent_project'] = $paymentSettings['URGENT_PROJECT_AMOUNT_CM'];
                    $this->outputData['hide_project'] = $paymentSettings['HIDE_PROJECT_AMOUNT_CM'];
                    $this->outputData['private_project'] = $paymentSettings['PRIVATE_PROJECT_AMOUNT_CM'];
                } else {
                    //Initital payment settings for projects
                    $paymentSettings = $this->settings_model->getSiteSettings();
                    $this->outputData['feature_project'] = $paymentSettings['FEATURED_PROJECT_AMOUNT'];
                    $this->outputData['urgent_project'] = $paymentSettings['URGENT_PROJECT_AMOUNT'];
                    $this->outputData['hide_project'] = $paymentSettings['HIDE_PROJECT_AMOUNT'];
                    $this->outputData['private_project'] = $paymentSettings['PRIVATE_PROJECT_AMOUNT'];
                }
            } else {
                $paymentSettings = $this->settings_model->getSiteSettings();
                $this->outputData['feature_project'] = $paymentSettings['FEATURED_PROJECT_AMOUNT'];
                $this->outputData['urgent_project'] = $paymentSettings['URGENT_PROJECT_AMOUNT'];
                $this->outputData['hide_project'] = $paymentSettings['HIDE_PROJECT_AMOUNT'];
                $this->outputData['private_project'] = $paymentSettings['PRIVATE_PROJECT_AMOUNT'];
            }
        }
    } //Constructor End 
    // --------------------------------------------------------------------

    /**
     * discard draft project by buyer
     *
     * @access    private
     * @param    nil
     * @return    void
     */
    function deleteDraft()
    {

        if ($this->uri->segment(3)) {
            $condition = array('draftprojects.id' => $this->uri->segment(3));
            $this->skills_model->deletedraftprojects($condition);
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('Draft Project Deleted Successfully')));
            redirect('project/create');
        }

    }

    /**
     * Post new projects by buyer
     *
     * @access    private
     * @param    nil
     * @return    void
     */
    function create()
    {
        $this->load->library('log_balance');
        $this->load->helper('transaction');
        $this->outputData['current_page'] = 'post_project';

        $result = '0';
        $manage = '1';
        $this->outputData['showPreview'] = false;

        //Load Language
        $this->lang->load('enduser/withdrawMoney', $this->config->item('language_code'));
        $this->lang->load('enduser/createBids', $this->config->item('language_code'));
        $this->lang->load('enduser/createProject', $this->config->item('language_code'));
        $this->lang->load('enduser/formValidation',$this->config->item('language_code'));

        $this->outputData['created'] = get_est_time();
        //$this->outputData['enddate']          = get_est_time() + ($this->input->post('openDays') * 86400);



        //Check For Buyer Session
        if (!isBuyer()) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged in as a buyer to post projects')));
            redirect('info');
        }
        if ($this->loggedInUser->suspend_status == 1) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('Suspend Error')));
            redirect('info');
        }
        //load validation libraray
        $this->load->library('form_validation');
        $this->load->library('upload');
        $this->load->library('images');
        //Load Form Helper
        $this->load->helper('form');
        $this->load->helper('file');
        $this->load->helper("bids_helper");
        //Load Category
        $condition = array('is_active' => 1);
        $this->outputData['groupCategories'] = $this->skills_model->getGroupsWithCategory($condition);
        $fields = array('categories.category_name');
        $this->outputData['categories'] = $this->skills_model->getCategories();

        //print_r($this->outputData['categories']);exit;
        //Intialize values for library and helpers	
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));

        if ($this->input->post('projectid')) {
            $project = $this->input->post('projectid');
        }

        // set value when buyer click post a same project
        $pid = $this->uri->segment(3,'');
        if(isset($pid) && !empty($pid) && is_numeric($pid)){
        	$condition = array("projects.id" => $pid);
        	$project = $this->skills_model->getProjects($condition);
        	if($project->num_rows() > 0){
        		$this->outputData['same_project'] = $same_project =  $project->row();
        	}
        
        	$this->outputData['categoryGroups'] = $this->skills_model->getCategories(NULL, "categories.id", explode(',',$same_project->group_ids));
            if(!empty($same_project)){
                $condition2 = array('groups.id' => $same_project->group_id);
                $groupParentSelect = $this->skills_model->getGroups($condition2)->row();
                $this->outputData['groupParentSelect'] = $groupParentSelect;

                $groupSelected = $this->skills_model->getGroups(array('groups.id' => $same_project->group_id))->row();				
                $condition3 = array('groups.parent_id' => $groupSelected->parent_id);
                $groupSelect = $this->skills_model->getGroups($condition3,array('groups.group_name','groups.id'))->result_array();
                $this->outputData['groupSelect'] = $groupSelect;
                $this->outputData['groupSelected'] = $groupSelected;

                $device_ids = explode(',', $same_project->device_ids);
                $devices = $this->skills_model->getDevices(null, 'project_device.project_categories', null, null, null, $device_ids);
                $categoryIds = '';
                foreach($devices->result() as $item){
                    $arrCategory = explode(',', $item->project_categories);
                    foreach($arrCategory as $key => $val){
                        $categoryIds[] = $val;
                    }
                }

                $categories = $this->skills_model->getCategories(null, 'categories.category_name, categories.id', $categoryIds);
                $this->outputData['stickySkill'] = $categories;				
            }
        }
        
        $condition = array('groups.is_deleted' => 0,'groups.parent_id' => 0);
        $fields = array('groups.group_name','groups.id');
        $this->outputData['groupParent'] = $this->skills_model->getGroups($condition,$fields);
        
        // load device
        $this->outputData['devices']= $this->skills_model->getProjectDevice(array('is_deleted' => 0));
        
        // load project template category
        $this->outputData['projectTemplates']= $this->skills_model->getProjectTemplates(array('project_templates.is_deleted' => 0));
        
        // load project template
        $templateId = $this->uri->segment(4,'');
        if($templateId != ''){
        	$condition2 = array('project_templates.is_deleted' => 0, 'project_templates.id' => $templateId);
        	$this->outputData['templateId'] = $templateId;
        	$this->outputData['projectTemplate'] = $projectTemplates = $this->skills_model->getProjectTemplates($condition2)->row();
        	$this->outputData['categoryGroups'] = $this->skills_model->getCategories(array("group_id" => $projectTemplates->group_id), "categories.id");
        	 
        	$condition2 = array('groups.id' => $projectTemplates->group_id);
        	$groupParentSelect = $this->skills_model->getGroups($condition2)->row();
        	$this->outputData['groupParentSelect'] = $groupParentSelect;
        
        	if(!empty($groupParentSelect)){
                $groupSelected = $this->skills_model->getGroups(array('groups.id' => $projectTemplates->group_id))->row();
                $condition3 = array('groups.parent_id' => $groupParentSelect->parent_id);
        		$groupSelect = $this->skills_model->getGroups($condition3,array('groups.group_name','groups.id'))->result_array();
        		$this->outputData['groupSelect'] = $groupSelect;
                $this->outputData['groupSelected'] = $groupSelected;
        	}
        }
        
        // load contries
        $this->outputData['countries'] = $this->skills_model->getCountries(NULL, NULL, NULL, array('0' => 30));
        
        //Get Form Data	
        if ($this->input->post('createProject')) {
            // Puhal Changes Start Following validations are to verify the post of Email address and Phone number (Sep 17 Issue 1)	-------------------------------------------		

            $this->form_validation->set_rules('project_name', 'lang:project_name_required', 'required|trim|xss_clean|alpha_space');
            $this->form_validation->set_rules('group[]', 'lang:group_required', 'required|trim|xss_clean');
            // Puhal Changes End Following validations are to verify the post of Email address and Phone number (Sep 17 Issue 1)	-------------------------------------------
            $this->form_validation->set_rules('description', 'lang:project_description_required', 'trim|xss_clean');
            //$this->form_validation->set_rules('project_categories', 'lang:category_required', 'required');//|callback_check_number_categories
            $this->form_validation->set_rules('budget', 'lang:budget', 'required|trim|xss_clean');


            if( $this->input->post('escrow_due',TRUE))  {
                $this->form_validation->set_rules('escrow_due', 'lang:escrow_required', 'trim|xss_clean|callback_check_escrow_due');
            }

 

            if(isset($_FILES['attachment']) == TRUE  and $_FILES['attachment']['name'] != ''){
            	$this->form_validation->set_rules('attachment', 'lang:file_required', 'callback_attachment_check_image');
            }

            $this->form_validation->set_message('required', '%s ' );
            $this->form_validation->set_message('is_unique', '%s ' . $this->lang->line('is_unique'));

            // load
            $this->outputData['categoryGroups'] = $this->skills_model->getCategories(NULL, "categories.id",$this->input->post('project_categories'));

            //load category child

            $groupSelect = $this->skills_model->getGroups(array('groups.parent_id' => $this->input->post('group_parent')),array('groups.group_name','groups.id'))->result_array();
            $this->outputData['groupSelect'] = $groupSelect;


            // load skills
            $device_ids = $this->input->post('device');
            $devices = $this->skills_model->getDevices(null, 'project_device.project_categories', null, null, null, $device_ids);
            $categoryIds = '';
            foreach($devices->result() as $item){
                $arrCategory = explode(',', $item->project_categories);
                foreach($arrCategory as $key => $val){
                    $categoryIds[] = $val;
                }
            }

            $categories = $this->skills_model->getCategories(null, 'categories.category_name, categories.id', $categoryIds);
            $this->outputData['categoryGroups'] = $categories;
            $this->outputData['stickySkill'] = $categories;

            if ($this->form_validation->run() == TRUE) {

                $insertData = array();
                $insertData['project_name'] = $this->input->post('project_name', TRUE);
                $insertData['description'] = $this->input->post('description', TRUE);
                //$insertData['project_categories'] = $this->input->post('project_categories');
                if( $this->input->post('escrow_due',TRUE)) {
                    $insertData['escrow_due'] = $this->input->post('escrow_due');
                }

                $array_categories = implode(',',$this->input->post('project_categories'));
                $insertData['project_categories'] = $array_categories;
                
                $list_project_categories = explode(',',$insertData['project_categories']);

                $fields = array('categories.id','categories.category_name');
                $condition = array('categories.is_deleted' => 0);
                $list_categories = $this->skills_model->getCategories($condition,$fields);

                $insertData['creator_id'] = $this->loggedInUser->id;
                $insertData['created'] = time();
                $insertData['enddate'] = time() + ($this->input->post('openDays') * 86400);
                //$insertData['attachment_avatar'] = $this->outputData['file']['file_name'];
                $insertData['flag'] = 1;
                $groupIds = $this->input->post('group');
                $insertData['group_id'] = $this->input->post('group_parent');
                $insertData['group_ids'] = implode(',',$groupIds);

                // add Freelancer Preferences
                $insertData['is_private'] = $this->input->post('is_private');
                $insertData['provider_rated'] = $this->input->post('provider_rated');
                $insertData['locations'] = implode(',',$this->input->post('locations'));
                if($this->input->post('device') != ''){
                    $insertData['device_ids'] = implode(',',$this->input->post('device'));
                }
                if((isset($this->outputData['file']))){
                    //print_r($this->outputData['file']);exit;
                    $optionImage = array (
                        'upload-dir' => ROOT_PATH.'/files/project_attachment',
                        'thumbs' => array (
                            array (
                                'width' => 226,
                                'height' => 195,
                                'type' => 'absolute',
                                'watermark' => false,
                                'override' => true
                            )) );
                    $this->images->resizeImage($this->outputData['file']['file_name'], $optionImage);

                    $insertData['attachment_avatar']    = $this->outputData['file']['file_name'];
//                    $thumb1 = $this->outputData['file']['file_path'].$this->outputData['file']['raw_name']."_thumb".$this->outputData['file']['file_ext'];
//                    GenerateThumbFile($this->outputData['file']['full_path'],$thumb1,226,195);
                }elseif(isset($projectTemplates) && $projectTemplates->images != ''){
                	$temImage = explode('|',$projectTemplates->images);
                	$insertData['attachment_avatar'] = $temImage[array_rand($temImage)];;
                }else{
                    $imageCondition = '';
                    if(isset($groupIds)){
                        foreach($groupIds as $key => $item){
                            if($imageCondition == ''){
                                $imageCondition .= "project_template_images.category_id = ".$item;
                            }else{
                                $imageCondition .= " OR project_template_images.category_id = ".$item;
                            }
                        }

                    }

                    // random image
                    $images = $this->skills_model->getTemplateImages($imageCondition, "project_template_images.url")->result_array();
                    if($images == null){
                        $images = $this->skills_model->getTemplateImages(null, "project_template_images.url")->result_array();
                    }
                    $insertData['attachment_avatar'] = $images[array_rand($images)]['url'];
                }
                switch($this->input->post('budget')){
                    case '1':
                        $insertData['budget_min'] = 30;
                        $insertData['budget_max'] = 250;
                        break;
                    case '2':
                        $insertData['budget_min'] = 250;
                        $insertData['budget_max'] = 750;
                        break;
                    case '3':
                        $insertData['budget_min'] = 750;
                        $insertData['budget_max'] = 1500;
                        break;
                    case '4':
                        $insertData['budget_min'] = 1500;
                        $insertData['budget_max'] = 3000;
                        break;
                    case '5':
                        $insertData['budget_min'] = 3000;
                        $insertData['budget_max'] = 5000;
                        break;
                    case '6':
                        $insertData['budget_min'] = 5000;
                        break;
                   	case '21':
                        $insertData['budget_min'] = 2;
                        $insertData['budget_max'] = 8;
                        break;
                    case '22':
                        $insertData['budget_min'] = 8;
                        $insertData['budget_max'] = 15;
                        break;
                    case '23':
                        $insertData['budget_min'] = 15;
                        $insertData['budget_max'] = 25;
                        break;
                    case '24':
                        $insertData['budget_min'] = 25;
                        $insertData['budget_max'] = 50;
                        break;
                    case '25':
                        $insertData['budget_min'] = 50;
                        break;
                    default:
                        $insertData['budget_min'] = $this->input->post('customize_budget_min');
                        $insertData['budget_max'] = $this->input->post('customize_budget_max');
                        break;
                }

                if ($id = $this->skills_model->createProject($insertData)) {
                	$this->load->helper("transaction");
                	$this->load->model("transaction_model");
                	//add transaction debit amount to frozen
                	$userInfo = getUserInfo($this->session->userdata['user_id']);
                	$escrow_due = $this->input->post('escrow_due');
                	
                	if(debitAmountToFrozen($userInfo->id, $escrow_due)){
                		$dataInsert = array(
                				'type' => "Debit amount to frozen",
                				'creator_id' => $userInfo->id,
                				'buyer_id' => $userInfo->id,
                				'transaction_time' => time(),
                				'amount' => $escrow_due,
                				'status' => "Completed",
                				'description' => "Trừ điểm đặt cọc dự án: ".$this->input->post('project_name'),
                				'user_type' => $userInfo->role_name,
                				'project_id' => $id,
                		);
                		$this->transaction_model->addTransaction($dataInsert);
                	}

                    if($this->input->get('backUrl',TRUE)){
                        redirect($this->input->get('backUrl',TRUE));
                    }

                    redirect('project/viewProjectAfterCreate/'.$id);
                }
            }
            //Form Validation End
        }
        //If - Form Submission End

        $this->load->view('project/createProject', $this->outputData);
    } //Function create End
    // --------------------------------------------------------------------

    function check_escrow_due(){
    	$this->load->helper("transaction");
    	
    	$user_id = $this->session->userdata['user_id'];
    	$escrow_due = $_POST['escrow_due'];
    	$escrow_min = $this->config->item("escrow_min");
    	$escrow_max = $this->config->item("escrow_max");
    	
    	if($escrow_min == 0 && $escrow_max == 0){
    		return TRUE;
    	}elseif($escrow_due > getAmountBalance($user_id)){ 
    		$this->form_validation->set_message('check_escrow_due', $this->lang->line('Amount not enough'));
    		return FALSE;
    	}elseif ($escrow_due < $escrow_min || $escrow_due > $escrow_max){
    		$this->form_validation->set_message('check_escrow_due', $this->lang->line('Escrow must be greater than ').$escrow_min.$this->lang->line(' and less than ').$escrow_max);
    		return FALSE;
    	}
    }

    //Puhal Changes Start for downloading the Project attachment file (Sep 20 Isssue 17)

    function download()
    {
        $this->load->library('zip');
        $this->load->helper('download');
        $this->load->helper('users');
        // initiallize the data variable in to array
        $this->data = array();

        // get the key value 
        $value = $this->uri->segment(3, 0);
        // Assign the base path.
        $base_path = base_url() . 'files/';
        $data = file_get_contents_curl($base_path . 'project_attachment/' . $value);
        $name = $value;
        // Apply the download function
        force_download($name, $data);
    }



//Puhal Changes End for downloading the Project attachment file (Sep 20 Isssue 17)


    /**
     * function create bid the programmer will create bid for the project
     *
     * @access    public for programmer
     * @param    nil
     * @return    void
     */
    function createBid()
    {
        //echo json_encode(array('data' => $this->input->post('data')));exit;
        //Load Language
        $this->lang->load('enduser/createBids', $this->config->item('language_code'));
        $this->lang->load('enduser/formValidation',$this->config->item('language_code'));

        //Check For Buyer Session
        if (!isProgrammer()) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged in as a Programmer to bid projects')));
            redirect('info');
        }

        //load validation libraray
        $this->load->library('form_validation');

        //Load Form Helper
        $this->load->helper('form');

        //Intialize values for library and helpers	
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag')."<br/>");

        //Get Form Data	
        //if ($this->input->post('postBid')) {
            //Set rules
            $this->form_validation->set_rules('bidAmt', 'lang:Your Bid', 'required|is_natural_no_zero|trim|xss_clean');
            $this->form_validation->set_rules('days', 'lang:Days', 'required|numeric|trim|xss_clean');;
            $this->form_validation->set_rules('bid_desc', 'lang:Bid desc', 'required|trim|xss_clean');
            $this->form_validation->set_rules('escrow_flag','lang:Milestone Request','required|trim|xss_clean|numeric');

            $this->form_validation->set_message('required', '%s ' . $this->lang->line('required'));
            $this->form_validation->set_message('is_natural_no_zero', '%s ' . $this->lang->line('is_natural_no_zero'));
            $this->form_validation->set_message('numeric','%s '.$this->lang->line('numeric'));

            if ($this->form_validation->run()) {
                $insertData = array();
                $insertData['project_id'] = $this->input->post('project_id');
                $insertData['user_id'] = $this->loggedInUser->id;
                $insertData['bid_days'] = $this->input->post('days');
                $insertData['bid_amount'] = $this->input->post('bidAmt');
                $insertData['bid_time'] = time();
                $insertData['bid_desc'] = $this->input->post('bid_desc');
                $insertData['escrow_flag'] = $this->input->post('escrow_flag');
                $insertData['bid_paid'] = $this->input->post('bid_paid');
                //echo json_encode(array('data' => $insertData));exit;
                //Create bids
                $id_bid = $this->skills_model->createBids($insertData);
                $condition = array('bids.id'=>$id_bid);
                $fields = array('bids.bid_amount','bids.bid_days','users.user_name');
                $last_bid = $this->skills_model->getBids($condition,$fields);
                //Notification message

                if($this->input->post('project_id') && $this->loggedInUser->id){
                    $messageData['project_id'] = $this->input->post('project_id');
                    $messageData['from_id'] = $this->loggedInUser->id;
                    $messageData['to_id'] = $this->input->post('creator_id');
                    $messageData['message'] = $this->lang->line('Message has bid');
                    $messageData['created'] = time();
                    $messageData['bids_id'] = $id_bid;
                    $messageData['type'] = 1;
                    $this->messages_model->postMessage($messageData);
                }

                $num_bid = getNumBid($this->input->post('project_id'));
                $data = array('status'=>'success','message' => $this->lang->line('Your bid Has Been Posted Successfully'),'id'=>$last_bid->result(),'num'=>$num_bid);
                echo json_encode($data);exit;
            } //Form Validation End
            else {
                $error = validation_errors();
                $data = array('status'=>'error','message'=>$error);
                echo json_encode($data);exit;
            }
        //}else{
           // echo "fail";exit;
       // }
        //If - Form Submission End

    } //Function create bid End
    // --------------------------------------------------------------------

    /**
     * Programmer will edit the placed bid for the project
     *
     * @access    public for programmer
     * @param    nil
     * @return    void
     */
    function editBid()
    {
        //Load Language
        $this->lang->load('enduser/formValidation', $this->config->item('language_code'));
        $this->lang->load('enduser/createBids', $this->config->item('language_code'));
        $this->lang->load('enduser/viewProject', $this->config->item('language_code'));
        //Check For Buyer Session
        if (!isProgrammer()) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged in as a Programmer to bid projects')));
            redirect('info');
        }

        //load validation libraray
        $this->load->library('form_validation');

        //Load Form Helper
        $this->load->helper('form');

        if($this->input->post('project_id')){
            $conditions = array('projects.id' => $this->input->post('project_id'));
            $fields = array('projects.id');
            $result = $this->skills_model->getProjects($conditions,$fields);
            $this->outputData['project'] = $result->row();
        }

        if (($this->input->post('project_id')) and isset($this->loggedInUser->id)) {
            $conditions = array('bids.user_id' => $this->loggedInUser->id, 'bids.project_id' => $this->input->post('project_id'));
            $fields = array('bids.id','bids.bid_days','bids.bid_amount','bids.bid_paid','bids.escrow_flag','bids.bid_desc');
            $this->outputData['bid'] = $this->skills_model->getBids($conditions,$fields);

        }

        //Intialize values for library and helpers	
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));

        //Get Form Data	
        if ($this->input->post('postBid')) {
            //Set rules
            $this->form_validation->set_rules('bidAmt', 'lang:Your Bid', 'required|is_natural_no_zero|trim|xss_clean');
            $this->form_validation->set_rules('days', 'lang:Days', 'required|numeric|trim|xss_clean');;
            $this->form_validation->set_rules('bid_desc', 'lang:Bid desc', 'required|trim|xss_clean');
            $this->form_validation->set_rules('escrow_flag','lang:Milestone Request','required|trim|xss_clean|numeric');

            $this->form_validation->set_message('required', '%s ' . $this->lang->line('required'));
            $this->form_validation->set_message('is_natural_no_zero', '%s ' . $this->lang->line('is_natural_no_zero'));
            $this->form_validation->set_message('numeric','%s '.$this->lang->line('numeric'));


            if ($this->form_validation->run()) {

                $updateData = array();
                $updateData['user_id'] = $this->loggedInUser->id;
                $updateData['bid_days'] = $this->input->post('days');
                $updateData['bid_amount'] = $this->input->post('bidAmt');
                //$updateData['bid_time'] = time();
                $updateData['bid_desc'] = $this->input->post('bid_desc');
                $updateData['escrow_flag'] = $this->input->post('escrow_flag');
                $updateData['bid_paid'] = $this->input->post('bid_paid');

                //Create bids

                $this->skills_model->updateBids($this->input->post('bidId'), $updateData);

                $data = array('status'=>'success','message' => $this->lang->line('Your bid Has Been Posted Successfully'));
                echo json_encode($data);exit;;
            } //Form Validation End
            else {
                $error = validation_errors();
                $data = array('status'=>'error','message'=>$error);
                echo json_encode($data);exit;
            }
        }

        //If - Form Submission End
        $this->load->view('project/editBid', $this->outputData);
    } //Function edit bid End
    // --------------------------------------------------------------------

    /**
     * Loads Categories page.
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function category()
    {
        //Load Language
        $this->lang->load('enduser/listProjects', $this->config->item('language_code'));
        $this->lang->load('enduser/editProfile', $this->config->item('language_code'));
        $this->lang->load('enduser/common', $this->config->item('language_code'));
        $this->lang->load('enduser/viewProject', $this->config->item('language_code'));

        //Get Category Id
        $category_id = $this->uri->segment(3, '0');


        //Page Title and Meta Tagsc
        $condition_key = array('categories.id' => $category_id);

        $result = $this->common_model->getPageTitle($condition_key,'categories');
        $result = $result->row();

        if (count($result) > 0) {
            $this->outputData['page_title'] = $result->page_title;
            $this->outputData['meta_keywords'] = $result->page_title;
            $this->outputData['meta_description'] = $result->meta_description;
        }

        //$category_name = replaceUnderscoreWithSpace($category_name);

        //Get current page
        $page = $this->uri->segment(4, '0');
        if (isset($page) === false or empty($page)) {
            $page = 1;
        }
        //Projects List
        //$like = array('project_categories' => $category_name);
        $order = array('id','desc');
        $conditions = array(
        		'projects.flag' => '1',
        		'projects.project_status' => '0',
        		'projects.is_deleted' => 0,
        		"FIND_IN_SET({$category_id}, project_categories) !=" => 0
        );
        $projects = $this->skills_model->getProjects($conditions, NULL, NULL);

        //Pagination
        $this->load->library('pagination');
        $config['base_url'] = site_url('project/category/' . $category_id);
        $config['total_rows'] = $projects->num_rows();
        $config['per_page'] = $this->config->item('listing_limit');

        $config['cur_page'] = $page;
        $this->outputData['page'] = $page;
        $this->pagination->initialize($config);
        $max = array($config['per_page'],($page - 1) * 10);
        $this->outputData['projects'] = $this->skills_model->getProjects($conditions, NULL, NULL, $max, $order);
        $this->outputData['groupCategories'] = $this->skills_model->getGroupsWithCategory();
        $this->outputData['pagination'] = $this->pagination->create_links(false, 'project');
        
        // load categories
        $this->outputData['groupCategories'] = $this->skills_model->getGroupsWithCategory();
        
        $this->load->view('project/listProjects', $this->outputData);
    } //Function category End
    // --------------------------------------------------------------------

    /**
     * Loads project view page.
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function view()
    {
        //Load Language
        $this->lang->load('enduser/common', $this->config->item('language_code'));
        $this->lang->load('enduser/viewProject', $this->config->item('language_code'));
        $this->lang->load('enduser/formValidation', $this->config->item('language_code'));
        $this->lang->load('enduser/createBids', $this->config->item('language_code'));
        $this->lang->load('enduser/milestone',$this->config->item('language_code'));


        $this->load->library('form_validation');
        $this->load->helper('users');
        $this->load->model("user_model");
        
        //Get Project Id
        if ($this->uri->segment(3)) {
            $project_id = $this->uri->segment(3, '0');

            if(!$this->loggedInUser){
                redirect("project/viewJobWhenUnregister/".$project_id);
            }

            $conditions = array('projects.id' => $project_id);
            $pr = $this->skills_model->getProjects($conditions);
            $pr = $pr->row();
            if(!empty($pr->project_categories)){
                $result  = $this->user_model->getUsersByUserCategory($pr->project_categories);
                if(count($result) > 0){
                    $this->outputData['userCate'] = $result;
                }else{
                    $this->outputData['userCate'] = 0;
                }                
            }else{
                $this->outputData['userCate'] = 0;
            }

            $conditions = array('projects.id' => $project_id);
            $this->outputData['projects'] = $this->skills_model->getProjects($conditions);
            $result = $this->outputData['projects'];
            $this->outputData['projectRow'] = $this->outputData['projects']->row();
            $project_detail = $result->result();
            $time = time();
            if(!$this->session->userdata('project_time_'.$project_id) || ($time - $this->session->userdata('project_time_'.$project_id) > 60 )){
                $this->session->set_userdata('project_time_'.$project_id,$time);
                $this->outputData['projectRow']->views += 1;
                $update['views'] = $this->outputData['projectRow']->views;
                $this->skills_model->updateProjects($project_id,$update);
            }
        }

        



        if (!is_numeric($this->uri->segment(3))) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You can not access to this page')));
            redirect('info');
        }
        if (isset($project_id) and isset($this->loggedInUser->id)) {
            $conditions = array('bids.user_id' => $this->loggedInUser->id, 'bids.project_id' => $project_id);
            $this->outputData['bid'] = $this->skills_model->getBids($conditions);
        }

        $fields_bid = array('bids.bid_amount','bids.bid_days','users.user_name','users.logo');
        $conditions_bid = array('projects.id' => $project_id);
        $orderby = array('bids.bid_time','desc');
        $this->outputData['listBid'] = $this->skills_model->getBids($conditions_bid,$fields_bid,null,null,$orderby);


        if ($this->outputData['projects']->num_rows() == 0) {
            //Notification message
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('project_not_available')));
            redirect('info');
        }

        //echo $this->outputData['projectRow']->creator_id;exit;
        $this->outputData['creatorInfo'] = getUserInfo($this->outputData['projectRow']->creator_id);

        $this->outputData['project'] = $this->outputData['projects']->row();

        if($this->outputData['project']->project_status != 0){
            $this->load->model('milestone_model');
            $this->outputData['cate_milestones'] = $this->milestone_model->getCateMilestone();
            $conditions = array('projects_id' => $this->outputData['project']->id);
            $fields = array('projects_milestones.name','projects_milestones.status','projects_milestones.fee','projects_milestones.id');
            $this->outputData['rows_projects_milestones'] = $this->milestone_model->getProjectsMilestone($conditions,$fields);

            $this->outputData['sum_milestone'] = $this->milestone_model->sumMilestone($conditions);

            $conditions_bid = array('bids.project_id' => $project_id,'bids.user_id' => $this->outputData['project']->programmer_id);
            $fields_bid = array('bids.bid_amount','bids.escrow_flag');
            $this->outputData['bids'] = $this->skills_model->getBids($conditions_bid,$fields_bid)->row();

            if(count($this->outputData['bids']) > 0)
            $this->outputData['sum_bid'] = $this->outputData['bids']->bid_amount - $this->outputData['bids']->escrow_flag;

            $conditions_file = array('projects_id' => $this->outputData['project']->id,'delete' => 0);
            $fields_file = array('title','description','path','id');
            $this->outputData['listDownloadFile'] = $this->file_model->getFile($conditions_file,$fields_file);

             
            $condition_message = array("project_id"=>$this->outputData['project']->id);
            $getMessage = $this->messages_model->getProjectMessage($condition_message);
            $this->outputData['allMessageProject'] = $getMessage->result();
        
        }

        $this->outputData['project_id'] = $project_id;

        $this->load->view('project/viewProject', $this->outputData);
    } //Function view End


    function addProjectMessage(){
        $this->load->model("messages_model");
        $projectID = $this->input->post("project_id",TRUE);
        $mContent = $this->input->post("m_content",TRUE);
        $condition = array("projects.id" => $projectID);
        $project_info = $this->skills_model->getUsersproject($condition);
        if($this->loggedInUser->id == $project_info->row()->creator_id){
            $sender = $project_info->row()->creator_id;
            $receiver = $project_info->row()->programmer_id;
        }elseif($this->loggedInUser->id == $project_info->row()->programmer_id){
            $sender = $project_info->row()->programmer_id;
            $receiver = $project_info->row()->creator_id;            
        }
        $insertData = array(
            "project_id"  => $projectID,
            "sender_id"   => $sender,
            "receiver_id" => $receiver,
            "content"     => $mContent,
            "date"     => time(),
            "is_delete"   => 0,
            "status"      => 0
        );

        $this->messages_model->addProjectMessage($insertData);
        echo json_encode(array("status"=>"success"));
    }// end funtion


    function showProjectMessage(){
        if($this->uri->segment(3)){
            $projectID = $this->uri->segment(3);
            $condition = array("project_id"=>$projectID);
            $getMessage = $this->messages_model->getProjectMessage($condition);
            $this->outputData['allMessageProject'] = $getMessage->result();
            /*echo "<pre>";
            print_r($getMessage->result());
            echo "</pre>";*/
        }
        
        $this->load->view("project/showProjectMessage",$this->outputData);
    }

    /**
     * Loads draft project view page.
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function draftView()
    {
        $projectid = $this->input->post('projectid1');

        //Load Language
        $this->lang->load('enduser/viewProject', $this->config->item('language_code'));
        $this->outputData['groupsWithCategories'] = $this->skills_model->getGroupsWithCategory();

        //Get Project Id
        $project_id = $this->input->post('draftId');

        $this->outputData['draftProjectsid'] = $project_id;
        $conditions = array('draftprojects.id' => $project_id);
        $this->outputData['projects'] = $this->skills_model->getDraft($conditions);

        if ($this->input->post('draftId') == 'clear') {
            redirect('project/deleteDraft/' . $projectid);
        }
        if ($this->input->post('draftId') == 'savedraft') {
            redirect('project/create');
        }
        if ($this->outputData['projects']->num_rows() == 0) {
            //Notification message
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('project_not_available')));
            redirect('info');
        }

        //Get Total Messages
        $this->load->model('messages_model');
        $message_conditions = array('messages.project_id' => $project_id);
        $this->outputData['totalMessages'] = $this->messages_model->getTotalMessages($message_conditions);
        $this->load->view('project/draftProject', $this->outputData);
    } //Function draftview End
    //-------------------------------------------------------------------------------------

    /**
     * Loads project view page.
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function previewProject()
    {
        //Load Language
        $this->lang->load('enduser/viewProject', $this->config->item('language_code'));

        //Get Project Id
        $project_id = $this->uri->segment(3, '0');
        $conditions = array('projects_preview.id' => $project_id);
        $this->outputData['projects'] = $this->skills_model->getpreviewProjects($conditions);
        //print_r($this->outputData['projects']->result());
        $this->load->view('project/previewProject', $this->outputData);
    } //Function previewProject End
    // --------------------------------------------------------------------

    /**
     * Loads postbid page.
     *
     * @access    public for programmer
     * @param    nil
     * @return    void
     */
    function postBid2()
    {
        //Load Language
        $this->lang->load('enduser/postBid', $this->config->item('language_code'));

        //Check For Programmer Session
        if (!isProgrammer()) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged in as a programmer to place a bid')));
            redirect('info');
        }
        if ($this->loggedInUser->suspend_status == 1) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('Suspend Error')));
            redirect('info');
        }
        //load validation libraray
        $this->load->library('form_validation');

        //Load Form Helper
        $this->load->helper('form');

        //Intialize values for library and helpers	
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));

        //Get Project Id
        if ($this->uri->segment(3)) {
            $project_id = $this->uri->segment(3, '0');
            $conditions = array('bids.user_id' => $this->loggedInUser->id, 'bids.project_id' => $project_id);
            $this->outputData['bid'] = $this->skills_model->getBids($conditions);
        } else {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You can not access to this page')));
            redirect('info');
        }
        if (!is_numeric($this->uri->segment(3))) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You can not access to this page')));
            redirect('info');
        }

        $conditions1 = array('projects.id' => $project_id);
        $this->outputData['projects'] = $this->skills_model->getProjects($conditions1);
        $this->outputData['project_id'] = $project_id;

        //Get Total Messages
        $this->load->model('messages_model');
        $message_conditions = array('messages.project_id' => $project_id);
        $this->outputData['totalMessages'] = $this->messages_model->getTotalMessages($message_conditions);

        //Get the favourite usersList
        $favourite_condition = array('user_list.creator_id' => $this->loggedInUser->id);
        $this->outputData['favourite'] = $this->user_model->getFavourite($favourite_condition);
        $this->load->view('project/postBid', $this->outputData);
    } //Function postBid End
    // --------------------------------------------------------------------

    /**
     * Loads check number categories for buyer

     */

    function check_number_categories()
    {
        $categories = $this->input->post('project_categories');
        
        //$categories = explode(",", $categories);
        if (count($categories) > 5) {
            $this->form_validation->set_message('check_number_categories', $this->lang->line('check_number_categories'));
            return false;
        } else {
            return true;
        }
    }


    /**
     * Loads attachment_check for buyer
     *
     * @access    public
     * @param    nil
     * @return    void
     */
    function attachment_check()
    {

        if (isset($_FILES) and $_FILES['attachment']['name'] == '')
            return true;

        $file = upload($_FILES, 'project_attachment', 'attachment');
        if (isset($file['file_name']) == TRUE) {
            $this->outputData['file'] = $file;
            return true;
        } else {
            $this->form_validation->set_message('attachment_check', $file);
            return false;
        }
        //If end 
    }//Function attachment_check End


    function attachment_check_image()
    {
        if (isset($_FILES['attachment']) == TRUE  and $_FILES['attachment']['name'] == ''){
            $this->form_validation->set_message('attachment_check_image',$this->lang->line('Image Required'));
            return false;
        }

        $file = upload_image($_FILES, 'project_attachment', 'attachment');
        if (isset($file['file_name']) == TRUE) {
            $this->outputData['file'] = $file;
            return true;
        } else {
            $this->form_validation->set_message('attachment_check_image', $this->lang->line($file));
            return false;
        }
        //If end 
    }//Function attachment_check End
    // --------------------------------------------------------------------

    function attachment_check_image_edit()
    {
        $file = upload_image($_FILES, 'project_attachment', 'attachment');
        if (isset($file['file_name']) == TRUE) {
            $this->outputData['file'] = $file;
            return true;
        } else {
            $this->form_validation->set_message('attachment_check_image', $file);
            return false;
        }
        //If end
    }//Function attachment_check_image End

// For Description field (Check for Phone number)
    function _phonenumber_check()
    {
        $description = $_POST['description'];
        //$reg = '/(\d)?(\s|-)?(\()?(\d){3}(\))?(\s|-){1}(\d){3}(\s|-){1}(\d){4}/';
        $reg = "/\(?[0-9]{3}\)?[-. ]?[0-9]{3}[-. ]?[0-9]{3}/";
        //$reg="/^(083|086|085|086|087)\d{7}$/";

        if (preg_match($reg, $description)) {
            $this->form_validation->set_message('_phonenumber_check', $this->lang->line('Phone not allowed'));
            return FALSE;
        } else {
            return TRUE;
        }

    }


// For project name  field (Check for Phone number) 		 
    function _phonenumber_projectname_check()
    {
        $projectName = $_POST['project_name'];
        //$reg = '/(\d)?(\s|-)?(\()?(\d){3}(\))?(\s|-){1}(\d){3}(\s|-){1}(\d){4}/';
        $reg = "/\(?[0-9]{1}\)?[-. ]?[0-9]{1}[-. ]?[0-9]{1}/";

        if (preg_match($reg, $projectName)) {

            $this->form_validation->set_message('_phonenumber_projectname_check', $this->lang->line('Phone not allowed'));
            return FALSE;
        } else {
            return TRUE;
        }

    }

// For Description field (Check for Email Address) 	
    function _emailpresent_check()
    {
        $description = $_POST['description'];
        $reg = '/[\s]*[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/';

        if (preg_match($reg, $description)) {

            $this->form_validation->set_message('_emailpresent_check',$this->lang->line('Email not allowed'));
            return FALSE;
        } else {
            return TRUE;
        }
    }

// For project name  field (Check for E-mail address) 	
    function _emailpresent_projectname_check()
    {
        $description = $_POST['project_name'];

        $reg = '/[\s]*[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/';

        if (preg_match($reg, $description)) {

            $this->form_validation->set_message('_emailpresent_projectname_check', $this->lang->line('Email not allowed'));
            return FALSE;
        } else {
            return TRUE;
        }

    }

// Puhal Changes End For the validation (Email and Phone number ) ----------------------------------------------------------

    /**
     * List bids on the particular project
     *
     * @access    public
     * @param    project id
     * @return    contents
     */
    function showBids()
    {
        //Load Language
        $this->lang->load('enduser/viewProject', $this->config->item('language_code'));
        $this->load->helper('users_helper');

        //Get Project Id
        $project_id = $this->uri->segment(3, '0');

        //Get Project details
        $conditions = array('projects.id' => $project_id);
        $project = $this->skills_model->getProjects($conditions);
        $this->outputData['projectRow'] = $project->row();

        $this->outputData['creatorInfo'] = getUserInfo($this->outputData['projectRow']->creator_id);
        $conditions = array('bids.project_id' => $project_id, 'projects.is_hide_bids' => 0);
        $order = $this->uri->segment(4, '0');
        $field = $this->uri->segment(5, '0');
        if ($order != 0)
            $orderby = array($field, $order);
        else
            $orderby = array();

        $this->outputData['bids'] = $this->skills_model->getBids($conditions, '', array(), array(), $orderby);
        //pr($this->outputData['bids']->result());exit;
        $this->outputData['ord'] = $order;
        $this->outputData['field'] = $field;
        $this->outputData['projectId'] = $project_id;

        if (isset($this->loggedInUser->id)) {
            $conditions = array('bids.user_id' => $this->loggedInUser->id, 'bids.project_id' => $project_id);
            $totbid = $this->skills_model->getBids($conditions);
            $this->outputData['tot'] = $totbid->row();
        } else
            $this->outputData['tot'] = array();
        $this->load->view('project/showBids', $this->outputData);
    }//Function showBids End
    // --------------------------------------------------------------------

    /**
     * List bids on the particular project to pick a Programmer
     *
     * @access    public for buyer to pick programmer
     * @param    project id
     * @return    contents
     */
    function pickProvider()
    {
        //Load Language
        $this->lang->load('enduser/pickProvider', $this->config->item('language_code'));

        //Get Project Id
        $project_id = $this->uri->segment(3, '0');
        $conditions = array('bids.project_id' => $project_id);

        $orderby = array('bid_amount', 'desc');

        $this->outputData['bids'] = $this->skills_model->getBids($conditions, '', array(), array(), $orderby);

      
        $this->load->view('project/pickProvider', $this->outputData);
    }//Function showBids End
    // --------------------------------------------------------------------

    /**
     * List all projects
     *
     * @access    public for buyer
     * @param    project id
     * @return    contents
     */
    function viewAllProjects()
    {
        //Load Language
        $this->lang->load('enduser/featuredProjects', $this->config->item('language_code'));
        $this->lang->load('enduser/common', $this->config->item('language_code'));
        $this->lang->load('enduser/editProfile', $this->config->item('language_code'));


        if ($this->input->post('customizeDisplay')) {
            //Get Customize data fields
            $this->session->set_userdata('show_cat', $this->input->post('show_cat', true));
            $this->session->set_userdata('show_budget', $this->input->post('show_budget', true));
            $this->session->set_userdata('show_bids', $this->input->post('show_bids', true));
            $this->session->set_userdata('show_avgbid', $this->input->post('show_avgbid', true));
            $this->session->set_userdata('show_status', $this->input->post('show_status', true));
            $this->session->set_userdata('show_date', $this->input->post('show_date', true));
            $this->session->set_userdata('show_desc', $this->input->post('show_desc', true));
            $this->session->set_userdata('show_num', $this->input->post('show_num', true));
        } else {
            $this->session->set_userdata('show_cat', '1');
            $this->session->set_userdata('show_budget', '1');
            $this->session->set_userdata('show_bids', '1');
            $this->session->set_userdata('show_num', '5');
        }
        //pr($this->session->userdata);
        $type = $this->uri->segment(3, '0');

        if ($type == 'is_feature')
            $this->outputData['pName'] = 'Featured Projects';
        if ($type == 'is_urgent')
            $this->outputData['pName'] = 'Urgent Projects';
        if ($type == 'all')
            $this->outputData['pName'] = 'Latest Projects';
        if ($type == 'high_budget')
            $this->outputData['pName'] = 'High Budget Projects';

        $page = $this->uri->segment(4, '0');
        //Get Sorting order
        $field = $this->uri->segment(5, '0');

        $order = $this->uri->segment(6, '0');
        $this->outputData['order'] = $order;
        $this->outputData['field'] = $field;
        $this->outputData['type'] = $type;
        $this->outputData['page'] = $page;
        if (isset($page) === false or empty($page)) {
            $page = 1;
        }
        $page_rows = $this->session->userdata('show_num');
        $max = array($page_rows, ($page - 1) * $page_rows);

        if ($type == 'all')
            $feature_conditions = array('projects.project_status' => '0');
        elseif ($type == 'high_budget')
            $feature_conditions = array('projects.project_status' => '0', 'budget_max >=' => '500');
        else
            $feature_conditions = array($type => 1, 'projects.project_status' => '0');
        $projects1 = $this->skills_model->getProjects($feature_conditions, NULL, NULL, $max);
        $projects = $this->skills_model->getProjects($feature_conditions);
        $this->outputData['featureProjects'] = $projects1;
        $this->load->library('pagination');
        $config['base_url'] = site_url('project/viewAllProjects/' . $type);
        $config['total_rows'] = $projects->num_rows();
        $config['per_page'] = $page_rows;
        $config['cur_page'] = $page;
        $this->pagination->initialize($config);
        $this->outputData['pagination'] = $this->pagination->create_links(false, 'project');
        $this->load->view('project/viewAllProjects', $this->outputData);
    }//Function showBids End
    // --------------------------------------------------------------------

    /**
     * List bids on the particular project to pick a Programmer
     *
     * @access    public
     * @param    project id
     * @return    contents
     */
    function awardBid()
    {
        //Load Language
        $this->lang->load('enduser/pickProvider', $this->config->item('language_code'));
        if ($this->input->post('pickBid') && $this->input->post('bidid') != '') {
            $bidid = $this->input->post('bidid',TRUE);
            $conditions = array('bids.id' => $bidid);
            $up = $this->skills_model->awardProject($conditions);

            if ($up == 1) {
                $fields = array('bids.escrow_flag','bids.bid_amount','projects.id','bids.id as bidid','projects.programmer_id','projects.creator_id');
                $bidres = $this->skills_model->getProjectByBid(array('bids.id' => $bidid),$fields);
                $bidres = $bidres->row();


                //print_r($bidres);exit;

                if($bidres->id && $this->loggedInUser->id){
                    $this->load->helper('transaction');

                    $frozen = $bidres->bid_amount - $bidres->escrow_flag;

                    $messageData['project_id'] = $bidres->id;
                    $messageData['from_id'] = $bidres->creator_id;
                    $messageData['to_id'] = $bidres->programmer_id;
                    $messageData['message'] = $this->lang->line('Message has bid');
                    $messageData['created'] = time();
                    $messageData['bids_id'] = $bidres->bidid;
                    $messageData['type'] = 2;
                    $this->messages_model->postMessage($messageData);

                    //gửi tin nhắn

                    debitAmount($bidres->creator_id,$bidres->escrow_flag);
                    updateFrozen($bidres->programmer_id,$bidres->escrow_flag);
                    debitAmount($bidres->creator_id,$frozen);
                    updateFrozen($bidres->creator_id,$frozen);

                    $insertData['from_id'] = $this->loggedInUser->id;
                    $insertData['to_id'] = $bidres->programmer_id;
                    $insertData['message'] = "";
                    $insertData['project_id'] = $bidres->id;
                    $insertData['created'] = time();
                    $insertData['type'] = 6;

                    $this->messages_model->postMessage($insertData);
                    // gửi message thông báo nhận được tiền.

                    $transactionData['creator_id'] = $this->loggedInUser->id;
                    $transactionData['buyer_id'] = $this->loggedInUser->id;
                    $transactionData['provider_id'] = $bidres->programmer_id;
                    $transactionData['transaction_time'] = time();
                    $transactionData['amount'] = $bidres->escrow_flag;
                    $transactionData['status'] = "Complete";
                    $transactionData['project_id'] = $bidres->id;

                    $this->transaction_model->addTransaction($transactionData);

                }
                //Update the notification status for the proejct to zero
                $updateKey = array('projects.id' => $bidres->id);
                $updateData['notification_status'] = '0';
                $this->skills_model->updateProjects(NULL, $updateData, $updateKey);

                redirect('buyer/viewMyProjects');

            } else {
                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('Please select the Provider')));

                redirect('buyer/viewMyProjects');
            }
        } else {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('Please select the Provider')));

            redirect('buyer/viewMyProjects');
        }

    }//Function awardbid End
    // --------------------------------------------------------------------

    /**
     * Accept project from Buyer who accepted your bid
     *
     * @access    public
     * @param    project id and checkstamp
     * @return    contents
     */
    function acceptProject()
    {
        //Load Language
        $this->lang->load('enduser/acceptProject', $this->config->item('language_code'));

        //Check For Programmer Session
        if (!isProgrammer()) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged in as a programmer to accept projects')));
            redirect('users/login');
        }


        $project_id = $this->uri->segment(3, '0');
        $checkstamp = $this->uri->segment(4, '0');

        if (isset($project_id)) {
            $updateKey = array('projects.id' => $project_id);
            $updateData['notification_status'] = '1';
            $this->skills_model->updateProjects(NULL, $updateData, $updateKey);
        }

        $conditions = array('projects.id' => $project_id, 'projects.checkstamp' => $checkstamp, 'projects.project_status' => '1', 'projects.programmer_id' => $this->loggedInUser->id);
        $project = $this->skills_model->getProjectsByAccept($conditions);
        $projectRow = $project->row();

        if (!is_object($projectRow)) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You cannot accept this project')));
            redirect('info');
        }

        //Check Ecrow Released or not

        $paymentSettings = $this->settings_model->getSiteSettings();
        $forced_escrow = $this->config->item('forced_escrow');
        if ($forced_escrow == 1) {
            $projectRow_id = $project_id;
            $condition = array('transactions.type' => 'Escrow Transfer', 'transactions.project_id' => $projectRow_id);
            $transactions = $this->transaction_model->getTransactions($condition);
            //$transactions->num_rows();
            $transactionrow = $transactions->row();
            if (!is_object($transactionrow)) {
                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You have not released the Escrow Amount')));
                redirect('info');
            } else {
                $status = $transactionrow->status;
                $escrow_projectid = $transactionrow->project_id;
                if ($status = '' or $escrow_projectid == '') {
                    $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You have not released the Escrow Amount.')));
                    redirect('info');
                }
            }

        }

        //Check User Balance
        $this->load->model('transaction_model');
        $this->load->helper("transaction");
        /* $condition_balance = array('user_balance.user_id' => $this->loggedInUser->id);
        $results = $this->transaction_model->getBalance($condition_balance); */
        /* if ($results->num_rows() > 0) { */
            //get balance detail
            /* $rowBalance = $results->row();
            $bal = $rowBalance->amount; */
        
            $min_bal = $this->config->item('payment_settings');
            $commission = $this->config->item('provider_commission_amount');
            // Puhal changes to get the % of the winning bid 

            $frozenBalance = getFrozenBalance($projectRow->userid);
            
            $cond = array('project_id' => $project_id, 'user_id' => $this->loggedInUser->id);
            $bid_amount = $this->common_model->getTableData('bids', $cond, 'bid_amount');
            $bid_amount_fetch = $bid_amount->row();

            $commission = ($commission * $bid_amount_fetch->bid_amount) / 100;
            $rem = $bid_amount_fetch->bid_amount - $commission;

            if ($frozenBalance < $min_bal || $rem < $min_bal) {
                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', 'Your account balance is too low'));
                redirect('programmer/viewMyProjects');
            }

            // debit frozen account buyer
            if(debitFrozen($projectRow->userid, $bid_amount_fetch->bid_amount)){
            	$dataInsert = array(
            			'type' => "Debit frozen",
            			'creator_id' => $projectRow->userid,
            			'buyer_id' => $projectRow->userid,
            			'transaction_time' => time(),
            			'amount' => $bid_amount_fetch->bid_amount,
            			'status' => "Completed",
            			'description' => "Debit frozen fee project",
            			'user_type' => $projectRow->role_name,
            			'project_id' => $projectRow->id,
            	);
            	$this->transaction_model->addTransaction($dataInsert);
            }
            
            $infoUser = getUserInfo($this->loggedInUser->id);
            // credit amount account programer
            if(creditAmount($this->loggedInUser->id, $rem)){
            	$dataInsert = array(
            			'type' => "Credit amount",
            			'creator_id' => $this->loggedInUser->id,
            			'buyer_id' => $this->loggedInUser->id,
            			'transaction_time' => time(),
            			'amount' => $rem,
            			'status' => "Completed",
            			'description' => "Credit amount free project",
            			'user_type' => $infoUser->role_name,
            			'project_id' => $projectRow->id,
            	);
            	$this->transaction_model->addTransaction($dataInsert);
            }
            
            /* $updateKey = array('user_balance.user_id' => $this->loggedInUser->id);
            $updateData = array('amount' => $rem);
            $results1 = $this->transaction_model->updateBalance($updateKey, $updateData); */

        /* } else {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', 'Your have no balance in your account to accept the projects'));
            redirect('programmer/viewMyProjects');
        } */


        $buyerId = $projectRow->creator_id;
        $programmerId = $projectRow->programmer_id;

        $conditions2 = array('users.id' => $buyerId);
        $buyer = $this->user_model->getUsers($conditions2);
        $buyerRow = $buyer->row();

        $conditions3 = array('users.id' => $programmerId);
        $programmer = $this->user_model->getUsers($conditions3);
        $programmerRow = $programmer->row();

        $updateKey = array(
            'projects.id' => $project_id,
            'projects.checkstamp' => $checkstamp,
            'projects.programmer_id' => $programmerId
        );
        $updateData = array('projects.project_status' => '2');
        $upProject = $this->skills_model->accpetProject($updateKey, $updateData);

        if (isset($project_id)) {

            //Load model
            $this->load->model('settings_model');
            $this->load->model('affiliate_model');

            // get projects for this user
            $condition = array('projects.id' => $project_id);
            $mpr = $this->skills_model->getProjects($condition);
            $prj = $mpr->row();


            // get user
            $condition = array('users.id' => $this->loggedInUser->id);
            $user_data = $this->user_model->getUsers($condition);

            //$user_data_result = $user_data->result();
            $user_data_row = $user_data->row();

            // get affiliate payments
            $affiliate_result = $this->affiliate_model->getAffiliatePayment();
            $buyer_affiliate_fee = $affiliate_result['buyer_affiliate_fee'];
            $programmer_affiliate_fee = $affiliate_result['programmer_affiliate_fee'];
            $buyer_min_payout = $affiliate_result['buyer_min_payout'];
            $programmer_min_payout = $affiliate_result['programmer_min_payout'];
            $buyer_project_fee = $affiliate_result['buyer_project_fee'];
            $programmer_project_fee = $affiliate_result['programmer_project_fee'];

            //get affiliate settings
            $settings = $this->settings_model->getSiteSettings();

            $provider_settings_fee = $settings['PROVIDER_COMMISSION_AMOUNT'];
            $featured_project_amount = $settings['FEATURED_PROJECT_AMOUNT'];

            if ($prj->project_status == 2 and $prj->programmer_id == $this->loggedInUser->id and $prj->checkstamp == $checkstamp) {

                if (isset($user_data_row->refid) and $user_data_row->refid != "0") {
                    $refid = $user_data_row->refid;
                    $role_id = $user_data_row->role_id;
                    $referral = $user_data_row->user_name;
                    $signup_date = $user_data_row->created;

                    $date_with_time = show_date($signup_date);
                    $arr_str = explode(',', $date_with_time);
                    $arr = explode(" ", trim($arr_str[1]));

                    for ($i = 0; $i < count($arr); $i++) {
                        $mon = $arr[1];
                        $year = $arr[2];
                    }

                    $signup_date_format = $mon . ", " . $year;

                    $conditions = array('bids.user_id' => $prj->programmer_id, 'bids.project_id' => $prj->id);
                    $totbid = $this->skills_model->getBids($conditions);
                    $result_bid = $totbid->row();

                    $bid_amount = $result_bid->bid_amount;

                    if ($role_id == 1) {

                        if ($prj->is_feature == 1) {
                            $featured_project_amount = $settings['FEATURED_PROJECT_AMOUNT'] * ($buyer_project_fee / 100);
                            $provider_percentage_amount = $bid_amount * ($provider_settings_fee / 100);
                            $commision = $provider_percentage_amount * ($buyer_project_fee / 100);
                            $commision_amount = $featured_project_amount + $commision;
                        } else {
                            $provider_percentage_amount = $bid_amount * ($provider_settings_fee / 100);
                            $commision_amount = $provider_percentage_amount * ($buyer_affiliate_fee / 100);
                        }


                        // insert affiliate sales
                        $clientdate = $this->config->item('clientdate');
                        $clienttime = $this->config->item('clienttime');
                        $clientbrowser = $this->config->item('clientbrowser');
                        $clientip = $this->config->item('clientip');

                        //prepare insert data
                        $insertData = array();
                        $insertData['refid'] = $refid;
                        $insertData['created_date'] = "$clientdate";
                        $insertData['created_time'] = "$clienttime";
                        $insertData['browser'] = "$clientbrowser";
                        $insertData['ipaddress'] = "$clientip";
                        $insertData['payment'] = $commision_amount;
                        $insertData['referral'] = $referral;
                        $insertData['account_type'] = $role_id;
                        $insertData['signup_date'] = $signup_date;
                        $insertData['signup_date_format'] = $signup_date_format;
                        //$insertData['is_released']='0';


                        //Add Category
                        $this->affiliate_model->addAffiliateSales($insertData);


                    }

                    if ($role_id == 2) {
                        if ($prj->is_feature == 1) {
                            $featured_project_amount = $settings['FEATURED_PROJECT_AMOUNT'] * ($programmer_project_fee / 100);
                            $provider_percentage_amount = $bid_amount * ($provider_settings_fee / 100);
                            $commision = $provider_percentage_amount * ($programmer_project_fee / 100);
                            $commision_amount = $featured_project_amount + $commision;

                        } else {
                            $programmer_percentage_amount = $bid_amount * ($provider_settings_fee / 100);
                            $commision_amount = $programmer_percentage_amount * ($programmer_affiliate_fee / 100);
                        }

                        // insert affiliate sales
                        $clientdate = $this->config->item('clientdate');
                        $clienttime = $this->config->item('clienttime');
                        $clientbrowser = $this->config->item('clientbrowser');
                        $clientip = $this->config->item('clientip');

                        //prepare insert data
                        $insertData = array();
                        $insertData['refid'] = $refid;
                        $insertData['created_date'] = "$clientdate";
                        $insertData['created_time'] = "$clienttime";
                        $insertData['browser'] = "$clientbrowser";
                        $insertData['ipaddress'] = "$clientip";
                        $insertData['payment'] = $commision_amount;
                        $insertData['referral'] = $referral;
                        $insertData['account_type'] = $role_id;
                        $insertData['signup_date'] = $signup_date;
                        $insertData['signup_date_format'] = $signup_date_format;
                        // $insertData['is_released']='0';
                        //print_r($insertData);

                        //Add Category
                        $this->affiliate_model->addAffiliateSales($insertData);


                    }

                } else {

                    // get user
                    $condition1 = array('users.id' => $prj->creator_id);
                    $user_data1 = $this->user_model->getUsers($condition1);
                    //$user_data_result = $user_data->result();
                    $user_data_row1 = $user_data1->row();
                    if (isset($user_data_row1->refid)) {
                        $refid = $user_data_row1->refid;
                        $role_id = $user_data_row1->role_id;
                        $referral = $user_data_row1->user_name;
                        $signup_date = $user_data_row->created;

                        $date_with_time = show_date($signup_date);
                        $arr_str = explode(',', $date_with_time);
                        $arr = explode(" ", trim($arr_str[1]));

                        for ($i = 0; $i < count($arr); $i++) {
                            $mon = $arr[1];
                            $year = $arr[2];
                        }

                        $signup_date_format = $mon . ", " . $year;

                        $conditions2 = array('bids.user_id' => $prj->programmer_id, 'bids.project_id' => $prj->id);
                        $totbid = $this->skills_model->getBids($conditions2);
                        $result_bid = $totbid->row();

                        $bid_amount = $result_bid->bid_amount;

                        if ($role_id == 1) {

                            if ($prj->is_feature == 1) {
                                $featured_project_amount = $settings['FEATURED_PROJECT_AMOUNT'] * ($buyer_project_fee / 100);
                                $provider_percentage_amount = $bid_amount * ($provider_settings_fee / 100);
                                $commision = $provider_percentage_amount * ($buyer_project_fee / 100);
                                $commision_amount = $featured_project_amount + $commision;
                            } else {
                                $provider_percentage_amount = $bid_amount * ($provider_settings_fee / 100);
                                $commision_amount = $provider_percentage_amount * ($buyer_affiliate_fee / 100);
                            }


                            // insert affiliate sales
                            $clientdate = $this->config->item('clientdate');
                            $clienttime = $this->config->item('clienttime');
                            $clientbrowser = $this->config->item('clientbrowser');
                            $clientip = $this->config->item('clientip');

                            //prepare insert data
                            $insertData = array();
                            $insertData['refid'] = $refid;
                            $insertData['created_date'] = "$clientdate";
                            $insertData['created_time'] = "$clienttime";
                            $insertData['browser'] = "$clientbrowser";
                            $insertData['ipaddress'] = "$clientip";
                            $insertData['payment'] = $commision_amount;
                            $insertData['referral'] = $referral;
                            $insertData['account_type'] = $role_id;
                            $insertData['signup_date'] = $signup_date;
                            $insertData['signup_date_format'] = $signup_date_format;
                            // $insertData['is_released']='0';


                            //Add Category
                            $this->affiliate_model->addAffiliateSales($insertData);


                        }

                        if ($role_id == 2) {
                            if ($prj->is_feature == 1) {
                                $featured_project_amount = $settings['FEATURED_PROJECT_AMOUNT'] * ($programmer_project_fee / 100);
                                $provider_percentage_amount = $bid_amount * ($provider_settings_fee / 100);
                                $commision = $provider_percentage_amount * ($programmer_project_fee / 100);
                                $commision_amount = $featured_project_amount + $commision;
                            } else {
                                $programmer_percentage_amount = $bid_amount * ($provider_settings_fee / 100);
                                $commision_amount = $programmer_percentage_amount * ($programmer_affiliate_fee / 100);
                            }


                            // insert affiliate sales
                            $clientdate = $this->config->item('clientdate');
                            $clienttime = $this->config->item('clienttime');
                            $clientbrowser = $this->config->item('clientbrowser');
                            $clientip = $this->config->item('clientip');

                            //prepare insert data
                            $insertData = array();
                            $insertData['refid'] = $refid;
                            $insertData['created_date'] = "$clientdate";
                            $insertData['created_time'] = "$clienttime";
                            $insertData['browser'] = "$clientbrowser";
                            $insertData['ipaddress'] = "$clientip";
                            $insertData['payment'] = $commision_amount;
                            $insertData['referral'] = $referral;
                            $insertData['account_type'] = $role_id;
                            $insertData['signup_date'] = $signup_date;
                            $insertData['signup_date_format'] = $signup_date_format;
                            //$insertData['is_released']='0';


                            //Add Category
                            $this->affiliate_model->addAffiliateSales($insertData);

                        }

                    }

                }


            }
        }

        if ($upProject == 1) {
            //Load Model For Mail
            $this->load->model('email_model');

            //Send Mail to Buyer
            $conditionUserMail = array('email_templates.type' => 'project_accepted_buyer');
            $result = $this->email_model->getEmailSettings($conditionUserMail);
            $rowUserMailConent = $result->row();

            $splVars = array("!programmer_username" => $programmerRow->user_name, "!project_title" => $projectRow->project_name, "!programmer_email" => $programmerRow->email, "!contact_url" => site_url('contact'));
            $mailSubject = $this->lang->line($rowUserMailConent->mail_subject);
            $mailContent = strtr($rowUserMailConent->mail_body, $splVars);
            $toEmail = $buyerRow->email;
            $fromEmail = $this->config->item('site_admin_mail');

            $this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);

            //Send Mail to Programmer
            $conditionUserMail2 = array('email_templates.type' => 'project_accepted_programmer');
            $result2 = $this->email_model->getEmailSettings($conditionUserMail2);
            $rowUserMailConent2 = $result2->row();

            $splVars2 = array("!project_title" => $projectRow->project_name, "!buyer_username" => $buyerRow->user_name, "!buyer_email" => $buyerRow->email, "!contact_url" => site_url('contact'));
            $mailSubject2 = $this->lang->line($rowUserMailConent2->mail_subject);
            $mailContent2 = strtr($rowUserMailConent2->mail_body, $splVars2);
            $toEmail2 = $programmerRow->email;
            $fromEmail2 = $this->config->item('site_admin_mail');
            $this->email_model->sendHtmlMail($toEmail2, $fromEmail2, $mailSubject2, $mailContent2);

            //Notification message
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('You have successfully accepted the project')));
            redirect('info/index/success');
        }



    }//Function acceptProject End
    // --------------------------------------------------------------------

    /**
     * deny project from programmer
     *
     * @access    public for programmer
     * @param    project id and checkstamp
     * @return    contents
     */
    function denyProject()
    {
        //Load Language
        $this->lang->load('enduser/denyProject', $this->config->item('language_code'));
        $project_id = $this->uri->segment(3, '0');
        $checkstamp = $this->uri->segment(4, '0');

        if (isset($project_id)) {
            $updateKey = array('projects.id' => $project_id);
            $updateData['notification_status'] = '1';
            $this->skills_model->updateProjects(NULL, $updateData, $updateKey);
        }

        $conditions = array('projects.id' => $project_id, 'projects.checkstamp' => $checkstamp, 'projects.project_status' => '1', 'projects.programmer_id' => $this->loggedInUser->id);
        $project = $this->skills_model->getProjects($conditions);
        $projectRow = $project->row();

        if (!is_object($projectRow)) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You cannot deny this project')));
            redirect('info');
        }

        $buyerId = $projectRow->creator_id;
        $programmerId = $projectRow->programmer_id;

        $conditions2 = array('users.id' => $buyerId);
        $buyer = $this->user_model->getUsers($conditions2);
        $buyerRow = $buyer->row();

        $conditions3 = array('users.id' => $programmerId);
        $programmer = $this->user_model->getUsers($conditions3);
        $programmerRow = $programmer->row();

        $updateKey = array(
            'projects.id' => $project_id,
            'projects.checkstamp' => $checkstamp,
            'projects.programmer_id' => $programmerId
        );
        $updateData = array('projects.project_status' => '0', 'projects.programmer_id' => '0');
        $upProject = $this->skills_model->accpetProject($updateKey, $updateData);

        if ($upProject == 1) {
            //Load Model For Mail
            $this->load->model('email_model');

            //Send Mail to Buyer
            $conditionUserMail = array('email_templates.type' => 'project_denied_buyer');
            $result = $this->email_model->getEmailSettings($conditionUserMail);
            $rowUserMailConent = $result->row();

            $splVars = array("!provider_username" => $programmerRow->user_name, "!project_title" => $projectRow->project_name, "!contact_url" => site_url('contact'));
            $mailSubject = $this->lang->line($rowUserMailConent->mail_subject);
            $mailContent = strtr($rowUserMailConent->mail_body, $splVars);
            $toEmail = $buyerRow->email;
            $fromEmail = $this->config->item('site_admin_mail');
            $this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);

            //Notification message
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('You have successfully denied the project')));
            redirect('info/index/success');
        }
    }//Function denyProject End
    // --------------------------------------------------------------------

    /**
     * Accept project from Buyer who accepted your bid
     *
     * @access    public
     * @param    project id and checkstamp
     * @return    contents
     */
    function postProject()
    {
        //language file
        $this->lang->load('enduser/review', $this->config->item('language_code'));

        //Check for Login details.
        if (!isset($this->loggedInUser->id)) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be login access to this page')));
            redirect('info');
        }
        if ($this->loggedInUser->role_id) {
            if ($this->loggedInUser->role_id == '2') {
                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged in as a buyer to post projects')));
                redirect('info');
            }
        }
        $project_id = $this->uri->segment(3, 0);

        //Initital payment settings for projects
        $paymentSettings = $this->settings_model->getSiteSettings();
        $this->outputData['feature_project'] = $paymentSettings['FEATURED_PROJECT_AMOUNT'];
        $this->outputData['urgent_project'] = $paymentSettings['URGENT_PROJECT_AMOUNT'];
        $this->outputData['hide_project'] = $paymentSettings['HIDE_PROJECT_AMOUNT'];

        //Get the project details for post similar projects
        $conditions = array('projects.id' => $project_id);
        $postSimilar = $this->skills_model->getUsersproject($conditions);
        $this->outputData['postSimilar'] = $postSimilar;

        //Laod the categories into the view page
        $this->outputData['groupsWithCategories'] = $this->skills_model->getGroupsWithCategory();
        $this->load->view('project/postProject', $this->outputData);
    }//Function acceptProject End
    // --------------------------------------------------------------------

    /**
     * manage project from Buyer who post project
     *
     * @access    public for buyer
     * @param    project id
     * @return    contents
     */
    function manageProject()
    {

        //Load Language
        $this->lang->load('enduser/createProject', $this->config->item('language_code'));
        $this->lang->load('enduser/project', $this->config->item('language_code'));
        $this->lang->load('enduser/review', $this->config->item('language_code'));
        //load validation libraray
        $this->load->library('form_validation');

        //Load Form Helper
        $this->load->helper('form');

        //Check for Login details.
        if (!isset($this->loggedInUser->id)) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be login access to this page')));
            redirect('info');
        }

        //Intialize values for library and helpers	
        $this->form_validation->set_error_delimiters($this->config->item('field_error_start_tag'), $this->config->item('field_error_end_tag'));

        if ($this->loggedInUser->role_id) {
            if ($this->loggedInUser->role_id == '2') {
                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged in as a buyer to post projects')));
                redirect('info');
            }
        }
        //Get Groups
        $this->outputData['groupsWithCategories'] = $this->skills_model->getGroupsWithCategory();

        if ($this->uri->segment(3, 0))
            $project_id = $this->uri->segment(3, 0);
        else
            $project_id = $this->input->post('projectid');
        //Get the project details for post similar projects
        $conditions = array('projects.id' => $project_id, 'projects.creator_id' => $this->loggedInUser->id);
        $postSimilar = $this->skills_model->getUsersproject($conditions);
        $this->outputData['postSimilar'] = $postSimilar;
        $res = $postSimilar->num_rows();
        //pr($postSimilar->result());
        if ($res <= 0) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('Your are not allow to manage this project')));
            redirect('project/view/' . $project_id);
        }

        if ($this->input->post('createProject')) {
            $this->form_validation->set_rules('budget_min', 'lang:budget_min_validation', 'trim|integer|is_natural|abs');
            $this->form_validation->set_rules('budget_max', 'lang:budget_max_validation', 'trim|integer|is_natural|integer|abs');
            $this->form_validation->set_rules('attachment', 'lang:attachment_validation', 'callback_attachment_check');
            $this->form_validation->set_rules('categories[]', 'lang:categories_validation', 'trim|integer|is_natural|abs|xss_clean|callback__maxvalcheckcat');

            if ($this->input->post('is_private')) {
                $this->form_validation->set_rules('private_list', 'lang:private_list', 'required|trim|');
            }
            if ($this->form_validation->run()) {
                //Initital payment settings for projects
                $paymentSettings = $this->settings_model->getSiteSettings();
                $this->outputData['feature_project'] = $feature_project = $paymentSettings['FEATURED_PROJECT_AMOUNT'];
                $this->outputData['urgent_project'] = $urgent_project = $paymentSettings['URGENT_PROJECT_AMOUNT'];
                $this->outputData['hide_project'] = $hide_project = $paymentSettings['HIDE_PROJECT_AMOUNT'];
                $private_project = $paymentSettings['PRIVATE_PROJECT_AMOUNT'];

                $res = $postSimilar->num_rows();

                if ($res <= 0) {
                    $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('Your are not allow to manage this project')));
                    redirect('project/view/' . $project_id);
                }

                //Create Projects before it for update the projects datas for manage option	   
                if ($this->input->post('update') == '0') {
                    if ($this->input->post('projectid')) {

                        //initial value set for check the featured , urgent, hide projects
                        $settingAmount = 0;

                        //check the values for featured, urgent, hide projects
                        if ($this->input->post('is_feature')) {
                            $settingAmount = $settingAmount + $feature_project;
                        }
                        if ($this->input->post('is_urgent')) {
                            $settingAmount = $settingAmount + $urgent_project;
                        }
                        if ($this->input->post('is_hide_bids')) {
                            $settingAmount = $settingAmount + $hide_project;
                        }
                        if ($this->input->post('is_private')) {
                            $settingAmount = $settingAmount + $private_project;
                        }
                        //Check User Balance
                        $condition_balance = array('user_balance.user_id' => $this->loggedInUser->id);
                        $results = $this->transaction_model->getBalance($condition_balance);

                        //If Record already exists
                        if ($results->num_rows() > 0) {
                            //get balance detail
                            $rowBalance = $results->row();

                            $this->outputData['userAvailableBalance'] = $rowBalance->amount;
                        }
                        if ($this->input->post('is_hide_bids', TRUE) or $this->input->post('is_urgent', TRUE) or $this->input->post('is_feature', TRUE) or $this->input->post('is_private', TRUE)) {
                            $withdrawvalue = $rowBalance->amount - ($settingAmount + $paymentSettings['PAYMENT_SETTINGS']);

                            if ($rowBalance->amount == 0) {
                                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('your not having sufficient balance')));
                                redirect('info');
                            } else if ($withdrawvalue < 0) {
                                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('your not having sufficient balance')));
                                redirect('info');
                            } else {
                                //Check User Balance
                                //Update Amount	
                                $updateKey = array('user_balance.user_id' => $this->loggedInUser->id);
                                $updateData = array();
                                $updateData['amount'] = $rowBalance->amount - $settingAmount;
                                $results = $this->transaction_model->updateBalance($updateKey, $updateData);

                                //Insert transaction for post projects
                                $insertTransaction = array();
                                $insertTransaction['creator_id'] = $this->loggedInUser->id;
                                $insertTransaction['type'] = $this->lang->line('Project Fee');
                                $insertTransaction['amount'] = $settingAmount;
                                $insertTransaction['transaction_time'] = get_est_time();
                                $insertTransaction['status'] = 'Completed'; //Can Be success,failed,pending

                                if ($this->input->post('is_feature')) {
                                    $insertTransaction['description'] = $this->lang->line('Project Fee for Feature Project');
                                }
                                if ($this->input->post('is_urgent')) {
                                    if (($insertTransaction['description']) != '') {
                                        $insertTransaction['description'] .= $this->lang->line('plus');
                                    }
                                    $insertTransaction['description'] = $this->lang->line('Project Fee for Urgent Project');
                                }
                                if ($this->input->post('is_hide_bids')) {
                                    if (($insertTransaction['description']) != '') {
                                        $insertTransaction['description'] .= $this->lang->line('plus');
                                    }
                                    $insertTransaction['description'] = $this->lang->line('Project Fee for hide bids Project');
                                }
                                if ($this->input->post('is_private')) {
                                    if (($insertTransaction['description']) != '') {
                                        $insertTransaction['description'] .= $this->lang->line('plus');
                                    }
                                    $insertTransaction['description'] = $this->lang->line('Project Fee for Private Project');
                                }
                                $insertTransaction['description'] .= $this->lang->line('Project Fee');

                                if ($this->loggedInUser->role_id == '1') {
                                    $insertTransaction['buyer_id'] = $this->loggedInUser->id;
                                    $insertTransaction['user_type'] = $this->lang->line('Project Fee for Bid');
                                }
                                if ($this->loggedInUser->role_id == '2') {
                                    $insertTransaction['provider_id'] = $this->loggedInUser->id;
                                    $insertTransaction['user_type'] = $this->lang->line('Project Fee for Bid');
                                }
                                $this->load->model('transaction_model');
                                $this->transaction_model->addTransaction($insertTransaction);
                            }
                        }

                        $insertData = array();
                        $insertData['project_name'] = $this->input->post('projectName');
                        $insertData['description'] = $this->input->post('description');


                        if (isset($this->data['file'])) {

                            $insertData['attachment_url'] = $this->data['file']['file_name'];
                            $insertData['attachment_name'] = $this->data['file']['orig_name'];
                        }

                        if ($this->input->post('update') == '0') {
                            $insertData['description'] = $this->input->post('description') . '<br/>';
                            $insertData['description'] .= $this->input->post('add_description');
                        } else
                            $insertData['description'] = $this->input->post('description');

                        $insertData['budget_min'] = $this->input->post('budget_min');
                        $insertData['budget_max'] = $this->input->post('budget_max');
                        if ($this->input->post('is_feature'))
                            $insertData['is_feature'] = $this->input->post('is_feature');
                        if ($this->input->post('is_urgent'))
                            $insertData['is_urgent'] = $this->input->post('is_urgent');
                        if ($this->input->post('is_hide_bids'))
                            $insertData['is_hide_bids'] = $this->input->post('is_hide_bids');
                        if ($this->input->post('is_private')) {
                            $insertData['is_private'] = $this->input->post('is_private');

                        }
                        $insertData['creator_id'] = $this->loggedInUser->id;
                        $insertData['created'] = get_est_time();
                        $insertData['enddate'] = get_est_time() + ($this->input->post('openDays') * 86400);
                        $result = '0';

                        if ($this->input->post('categories')) {
                            $categories = $this->input->post('categories');

                            //Work With Project Categories
                            $project_categoriesNameArray = $this->skills_model->convertCategoryIdsToName($categories);
                            $project_categoriesNameString = implode(',', $project_categoriesNameArray);
                            $insertData['project_categories'] = $project_categoriesNameString;
                        }

                        //Update the data
                        $project = $this->input->post('projectid');
                        $condition = array('projects.id' => $project);

                        $this->skills_model->manageProjects($insertData, $condition);

                        if ($this->input->post('is_private')) {

                            $private_users = $this->input->post('private_list', TRUE);

                            if ($private_users != '') {
                                $private_users_array = explode("\n", $private_users);
                                $condition = '`role_id`=2';
                                foreach ($private_users_array as $val) {
                                    $private_users_array1[] = " `user_name`='" . $val . "'";
                                }
                                $private_users_str1 = implode(' OR ', $private_users_array1);
                                $private_users_cond = $condition . ' AND (' . $private_users_str1 . ')';
                                //$sel_users=$this->user_model->getUsersfromusername($condition=array(),$private_users_array,NULL);
                                $sel_users = $this->user_model->getUsersfromusername($private_users_cond);
                                //pr($sel_users->result());
                                if ($sel_users->num_rows() > 0) {
                                    foreach ($sel_users->result() as $users) {
                                        $pusers[] = $users->id;
                                    }
                                    $pusers = array_unique($pusers);
                                    $pusers1 = implode(',', $pusers);
                                    $data = array('private_users' => $pusers1);
                                    $condition = array('id' => $project);
                                    $table = 'projects';

                                    $this->common_model->updateTableData($table, NULL, $data, $condition);
                                    //insert project_invitation table for private users
                                    $insertprivate = array('project_id' => $project, 'sender_id' => $this->loggedInUser->id, 'invite_date' => get_est_time(), 'notification_status' => '0');
                                    $invitetable = 'project_invitation';
                                    foreach ($pusers as $val) {
                                        $insertprivate['receiver_id'] = $val;

                                        $this->common_model->insertData($invitetable, $insertprivate);
                                    }
                                }
                            }

                        }

                        if ($this->input->post('is_private')) {
                            //Send Mail
                            $conditionProviderMail = array('email_templates.type' => 'private_project_provider');
                            $resultProvider = $this->email_model->getEmailSettings($conditionProviderMail);
                            $resultProvider = $resultProvider->row();

                            $projectpage = site_url('project/view/' . $project);

                            $splVars_provider = array("!site_name" => $this->config->item('site_title'), "!projectname" => $this->input->post('projectName'), "!creatorname" => $this->loggedInUser->user_name, "!profile" => $project_categoriesNameString, "!projectid" => $project, "!date" => get_datetime(time()), "!projecturl" => $projectpage,);


                            //pr($sel_users->result());
                            //sending emailto all the providers
                            if ($private_users != '') {

                                if ($sel_users->num_rows() > 0) {
                                    foreach ($sel_users->result() as $users) {
                                        $insertMessageData['project_id'] = $project;
                                        $insertMessageData['to_id'] = $users->id;
                                        $insertMessageData['from_id'] = $this->loggedInUser->id;
                                        $insertMessageData['message'] = "Private Project Notification --> You are Invited for the private project<br/>Follow the link given below to view the project<br/>" . site_url('project/view/' . $project);
                                        $insertMessageData['created'] = get_est_time();
                                        //pr($insertMessageData); exit;
                                        $this->messages_model->postMessage($insertMessageData);

                                        if ($users->email != '') {
                                            $toEmail_provider = $users->email;
                                            $fromEmail_provider = $this->config->item('site_admin_mail');


                                            $selusernames[] = $users->user_name;
                                            $splVars_provider['!username'] = $users->user_name;
                                            $mailSubject_provider = strtr($resultProvider->mail_subject, $splVars_provider);
                                            $mailContent_provider = strtr($resultProvider->mail_body, $splVars_provider);
                                            $this->email_model->sendHtmlMail($toEmail_provider, $fromEmail_provider, $mailSubject_provider, $mailContent_provider);

                                        }
                                    }
                                }

                            }
                        }
                        if ($this->input->post('is_private')) {
                            $conditionUserMail = array('email_templates.type' => 'privateproject_post');
                            $result = $this->email_model->getEmailSettings($conditionUserMail);
                            $rowUserMailConent = $result->row();
                            $splVars = array("!site_name" => $this->config->item('site_title'), "!projectname" => $this->input->post('projectName'), "!username" => $this->loggedInUser->user_name, "!profile" => $project_categoriesNameString, "!projectid" => $project, "!projectid" => $project, "!date" => get_datetime(time()));
                            if ($private_users != '') {
                                if ($sel_users->num_rows() > 0) {
                                    $selusernamesstr = implode(",", $selusernames);
                                } else {
                                    $selusernamesstr = '';
                                }
                            } else {
                                $selusernamesstr = '';
                            }
                            $splVars['!privateproviders'] = $selusernamesstr;
                            $mailSubject = strtr($rowUserMailConent->mail_subject, $splVars);
                            $mailContent = strtr($rowUserMailConent->mail_body, $splVars);

                            $toEmail = $this->loggedInUser->email;
                            $fromEmail = $this->config->item('site_admin_mail');
                            $this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);
                        } else {
                            //Send Mail
                            $conditionUserMail = array('email_templates.type' => 'projectpost_notification');
                            $result = $this->email_model->getEmailSettings($conditionUserMail);
                            $rowUserMailConent = $result->row();
                            $splVars = array("!site_name" => $this->config->item('site_title'), "!projectname" => $insertData['project_name'], "!username" => $this->loggedInUser->user_name, "!profile" => $project_categoriesNameString, "!projectid" => $this->db->insert_id(), "!projectid" => $this->db->insert_id(), "!date" => get_datetime(time()));
                            $mailSubject = strtr($rowUserMailConent->mail_subject, $splVars);
                            $mailContent = strtr($rowUserMailConent->mail_body, $splVars);

                            $toEmail = $this->loggedInUser->email;
                            $fromEmail = $this->config->item('site_admin_mail');
                            $this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);
                        }

                        //Notification message
                        //Load Model For Mail
                        $this->load->model('email_model');

                        //Send Mail
                        $conditionUserMail = array('email_templates.type' => 'projectpost_notification');
                        $result = $this->email_model->getEmailSettings($conditionUserMail);
                        $rowUserMailConent = $result->row();
                        $splVars = array("!site_name" => $this->config->item('site_title'), "!username" => $this->loggedInUser->user_name, "!projectid" => $this->db->insert_id(), "!date" => get_datetime(time()));
                        $mailSubject = strtr($rowUserMailConent->mail_subject, $splVars);
                        $mailContent = strtr($rowUserMailConent->mail_body, $splVars);
                        $toEmail = $this->loggedInUser->email;
                        $fromEmail = $this->config->item('site_admin_mail');

                        $this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);

                        $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('Your Project has been Updated Successfully')));
                        redirect('buyer/viewMyProjects');
                    }
                }
                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('Your Project has been Updated Successfully')));
                redirect('buyer/viewMyProjects');
            }
        }
        $this->load->view('project/manageProject', $this->outputData);

    }//Function acceptProject End
    // --------------------------------------------------------------------

    /**
     * Post report regardign the project violation
     *
     * @access    public for programmer
     * @param    project id
     * @return    contents
     */
    function postReport()
    {
        //Load Language
        $this->lang->load('enduser/createProject', $this->config->item('language_code'));
        $project_id = $this->uri->segment(3, 0);
        $conditions = array('projects.id' => $project_id);
        $postSimilar = $this->skills_model->getUsersproject($conditions);
        $this->outputData['postSimilar'] = $postSimilar;
        $res = $postSimilar->num_rows();
        if ($this->input->post('submitReport')) {
            $insertData['id'] = '';
            $insertData['project_id'] = $project_id;
            $insertData['project_name'] = $this->input->post('projectname');
            $insertData['post_id'] = $this->loggedInUser->id;
            $insertData['post_name'] = $this->loggedInUser->user_name;
            $insertData['comment'] = $this->input->post('report');
            $insertData['report_date'] = get_est_time();
            $insertData['report_type'] = 'Project Report';

            //insert the report contents into the project_reports table
            $this->skills_model->insertReport($insertData);
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('Your report has been send successfully')));
            redirect('project/postReport/' . $project_id);
        }
        $this->load->view('project/projectReport', $this->outputData);
    }//Function acceptProject End
    // --------------------------------------------------------------------

    /**
     * Post project bid report violation
     *
     * @access    public for buyer
     * @param    project id
     * @return    contents
     */
    function postBidReport()
    {
        //Load Language
        $this->lang->load('enduser/createProject', $this->config->item('language_code'));

        if ($this->uri->segment(3)) {
            $bid_id = $this->uri->segment(3);
            //Get the bids details
            $bid_condition = array('bids.id' => $bid_id);
            $getBids = $this->skills_model->getBids($bid_condition);
            $this->outputData['getBids'] = $getBids;
            $getBids = $getBids->row();

            //Get projects details
            $project_condition = array('projects.id' => $getBids->project_id);
            $postSimilar = $this->skills_model->getUsersproject($project_condition);
            $this->outputData['postSimilar'] = $postSimilar;

            //Get users details
            $user_condition = array('users.id' => $getBids->user_id);
            $getUsers = $this->user_model->getUsers($user_condition);
            $this->outputData['getUsers'] = $getUsers;

            $res = $postSimilar->num_rows();
        }
        if ($this->input->post('submitReport')) {
            $insertData['id'] = '';
            $project_id = $this->input->post('projectid');
            $insertData['project_id'] = $project_id;
            $insertData['project_name'] = $this->input->post('projectname');
            $insertData['post_id'] = $this->loggedInUser->id;
            $insertData['post_name'] = $this->loggedInUser->user_name;
            $insertData['comment'] = $this->input->post('report');
            $insertData['report_date'] = get_est_time();
            $insertData['report_type'] = 'Bid Report';
            //insert the report contents into the project_reports table
            $this->skills_model->insertReport($insertData);
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('Your report has been send successfully')));
        }
        $this->load->view('project/bidProjectReport', $this->outputData);
    }//Function acceptProject End
    // --------------------------------------------------------------------

    /**
     * Create invoice report for the logged user
     *
     * @access    private
     * @param    project id and checkstamp
     * @return    contents
     */
    function invoice()
    {
        //Innermenu tab selection
        $this->outputData['innerClass8'] = '';
        $this->outputData['innerClass8'] = 'selected';

        if (!isset($this->loggedInUser->id)) {

            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You can not access to this page')));
            redirect('info');
        }
        $check = '0';
        //Check will assign to 1 while the invoice submittion
        if ($this->input->post('invoice')) {

            $check = '1';
        }

        //Load Language
        $this->lang->load('enduser/createProject', $this->config->item('language_code'));
        $this->lang->load('enduser/invoice', $this->config->item('language_code'));
        if ($check == '0') {
            $project_id = $this->uri->segment(3, 0);

            //Get the project details for post similar projects
            $conditions = array('projects.creator_id' => $this->loggedInUser->id, 'projects.project_status' => '2', 'projects.project_paid' => '1');
            $invoiceProject = $this->skills_model->getUsersproject($conditions);
            $this->outputData['invoiceProject'] = $invoiceProject;
            $this->outputData['postSimilar'] = $invoiceProject;
            $count = $invoiceProject->num_rows();
            $res = $invoiceProject->num_rows();
        }

        //Check User Balance
        $condition_balance = array('user_balance.user_id' => $this->loggedInUser->id);
        $results = $this->transaction_model->getBalance($condition_balance);

        //If Record already exists
        if ($results->num_rows() > 0) {
            //get balance detail
            $rowBalance = $results->row();
            $this->outputData['userAvailableBalance'] = $rowBalance->amount;
        }

        //Load the view for the invoice
        if ($check == '0') {
            $this->load->view('project/projectInvoice', $this->outputData);
        } else {
            $this->outputData['project_name'] = $this->input->post('project_name');
            $this->outputData['user_name'] = $this->input->post('user_name');
            $this->outputData['bidsProjects'] = $this->input->post('invoice');
            $this->outputData['invoice_no'] = $this->input->post('invoice_no');
            $this->outputData['bidsProjects'] = $this->skills_model->getBidsproject();
            $this->load->view('project/invoice', $this->outputData);
        }
    }//Function invoice End
    // --------------------------------------------------------------------

    /**
     * Create invite report for the logged user
     *
     * @access    private
     * @param    project id and checkstamp
     * @return    contents
     */
    function inviteUser()
    {
        //Load Language
        $this->lang->load('enduser/userlist', $this->config->item('language_code'));
        if ($this->loggedInUser) {
            $userid = $this->loggedInUser->id;
            $condition = array('projects.creator_id' => $userid);
            $res = $this->skills_model->getUsersproject($condition);
            if ($res->num_rows() > 0) {
                $condition = array('user_list.creator_id' => $this->loggedInUser->id);
                $this->outputData['favouriteList'] = $this->user_model->getFavourite($condition);
                $this->load->view('buyer/inviteProgrammer', $this->outputData);
            } else {
                //Notification message
                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be post project to invite programmers')));
                redirect('info');
            }
        } else {
            //Notification message
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged to invite programmers')));
            redirect('info');
        }
    }//Function inviteUser End

    // --------------------------------------------------------------------

    /**
     * Check and close the projects if their bidding end date is expired.
     *
     * @access    private
     * @param    project id and checkstamp
     * @return    contents
     */
    function biddingEndCheck()
    {
        $projects = $this->skills_model->getProjects();
        foreach ($projects->result() as $res) {
            $diff = $res->enddate - get_est_time();
            if ($diff == 0) {
                $updateKey = array('projects.id' => $res->id);
                $updateData = array('projects.project_status' => '3');
                $this->skills_model->updateProjects(NULL, $updateData, $updateKey);

                //Load Model For Mail
                $this->load->model('email_model');

                //Send Mail
                $conditionUserMail = array('email_templates.type' => 'project_cancelled');
                $result = $this->email_model->getEmailSettings($conditionUserMail);
                $rowUserMailConent = $result->row();

                $splVars = array("!buyer_name" => $res->user_name, "!project_name" => $res->project_name, "!contact_url" => site_url('contact'));
                $mailSubject = strtr($rowUserMailConent->mail_subject, $splVars);
                $mailContent = strtr($rowUserMailConent->mail_body, $splVars);
                $toEmail = $res->email;
                $fromEmail = $this->config->item('site_admin_mail');
                $this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);
            }
        }
    }//Function biddingEndCheck End

    // --------------------------------------------------------------------

    /**
     * Sending new project notifications to Providers
     *
     * @access    private
     * @param    project id and checkstamp
     * @return    contents
     */
    function newProjectsNotify()
    {
        //Load Models
        $this->load->model('search_model');

        $yesterday = date('j/n/Y', mktime(0, 0, 0, date("m"), date("d") - 1, date("Y")));

        $conditions = array('users.role_id' => '2', 'users.user_status' => '1', 'user_categories.user_categories !=' => '');

        $users = $this->user_model->getUsersWithCategories($conditions);
        $prids = array();
        $i = 0;
        foreach ($users->result() as $user) {
            $cate = explode(",", $user->user_categories);
            //Get projects by categories
            foreach ($cate as $cat) {
                $cond = array('categories.id' => $cat);
                $res = $this->skills_model->getCategories($cond);
                $row = $res->row();
                $cname = $row->category_name;
                $like = array('projects.project_categories' => $cname);
                $conditions2 = array("FROM_UNIXTIME( projects.created, '%e/%c/%Y' ) = " => $yesterday, 'projects.project_status' => '0');
                $projects = $this->search_model->getProjects($conditions2, 'projects.id', $like);
                foreach ($projects->result() as $prid) {
                    $prids[$i] = $prid->id;
                    $i++;
                }

            }
            $prids = array_unique($prids);
            $mailSubject = $this->config->item('site_title') . " Project Notice";
            $mailContent = "The following " . count($prids) . " projects were recently added to " . $this->config->item('site_title') . " and match your expertise:<br><br>";
            foreach ($prids as $prj) {
                $condition3 = array('projects.id' => $prj);
                $mpr = $this->skills_model->getProjects($condition3);
                $prj = $mpr->row();
                $mailContent .= $prj->project_name . " (Posted by " . $prj->user_name . ", " . get_datetime($prj->created) . ", Job type:" . $prj->project_categories . ")" . "<br>" . site_url('project/view/' . $prj->id) . "<br><br>";
            }
            //Send mail
            $toEmail = $user->email;
            $fromEmail = $this->config->item('site_admin_mail');
            $this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);
        }
    }//Function biddingEndCheck End

    // --------------------------------------------------------------------

    /**
     * Extend project bid
     *
     * @access    private
     * @param    project id and checkstamp
     * @return    contents
     */
    function extendBid()
    {
        //Load Language
        $this->lang->load('enduser/viewProject', $this->config->item('language_code'));
        if ($this->input->post('extend')) {
            $prjid = $this->input->post('projectid');
            $condition2 = array('projects.id' => $prjid);
            $res = $this->skills_model->getProjects($condition2);
            $row = $res->row();
            $left = days_left($row->enddate, $prjid);
            if ($left == 'Closed')
                $enddate = get_est_time() + ($this->input->post('openDays') * 86400);
            else {
                $today = time();
                $lastday = $row->enddate;
                $left = $lastday - $today;
                $val = date('j', $left);
                $open = $val + $this->input->post('openDays');
                $enddate = get_est_time() + ($open * 86400);

            }

            $updateKey = array('projects.id' => $this->input->post('projectid'));
            $updateData = array('projects.enddate' => $enddate, 'projects.project_status' => '0');
            $this->skills_model->updateProjects(NULL, $updateData, $updateKey);

            //Notification message
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('Your project bid has been extended')));
            redirect('buyer/viewMyProjects');
        }
        $prjid = $this->uri->segment(3, '0');
        $condition = array('projects.id' => $prjid);
        $this->outputData['project'] = $this->skills_model->getProjects($condition);
        $this->load->view('buyer/extend', $this->outputData);
    }//Function extendBid End
//------------------------------------------------------------------------------------------

    /**
     * calculate the consolidate bids details after 12 hr and send email to the buyer
     *
     * @access    private
     * @param    nil
     * @return    void
     */
    function bidConsolidate()
    {
        //Get all users details
        $projects = $this->skills_model->getProjects();
        foreach ($projects->result() as $res) {
            $records = '';
            $diff = count_days($res->created, get_est_time());
            if ($diff > 0) {
                $projectid = $res->id;
                $projectname = $res->project_name;
                //Get all bids details for the project
                $bid_condition = array('bids.project_id' => $projectid);
                $bids = $this->skills_model->getBids($bid_condition);
                if (isset($bids) and count($bids->result()) > 0) {
                    $i = 1;
                    $records .= '<table border="1"><tr><th align="center">Sl.No</th><th width="300">Project Name</th>	<th width="250">Username</th> <th width="100" align="center">Bid Amount</th> <th width="250" align="center">Bid Post Time</th></tr>';
                    foreach ($bids->result() as $bids) {
                        $user_condition = array('users.id' => $bids->user_id);
                        $users = $this->user_model->getUsers($user_condition);
                        $user = $users->row();
                        $records .= '<tr><td align="center">' . $i++ . '</td><td>' . $res->project_name . '</td><td>' . $user->user_name . '</td><td align="center">' . '$ ' . $bids->bid_amount . '</td><td align="center">' . get_datetime($bids->bid_time) . '</td></tr>';
                    }

                    $records .= '</table>';

                    $user_condition = array('users.id' => $res->creator_id);
                    $creator = $this->user_model->getUsers($user_condition);
                    $creator = $creator->row();
                    //Send Mail to project creator
                    $conditionUserMail = array('email_templates.type' => 'consolidate_bids');
                    $result = $this->email_model->getEmailSettings($conditionUserMail);
                    $rowUserMailConent = $result->row();
                    //Update the details 
                    $splVars = array("!projectname" => '<a href="' . site_url('project/view/' . $res->id) . '">' . $res->project_name . '</a>', "!username" => $creator->user_name, "!contact_url" => site_url('contact'), "!site_url" => site_url(), '!site_name' => $this->config->item('site_title'), '!records' => $records);
                    $mailSubject = strtr($rowUserMailConent->mail_subject, $splVars);
                    $mailContent = strtr($rowUserMailConent->mail_body, $splVars);
                    $toEmail = $creator->email;
                    $fromEmail = $this->config->item('site_admin_mail');
                    $this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);
                }
            }
        }
    } //Function bidConsolidate end

    // --------------------------------------------------------------------

    /**
     * Sending new project notifications every hour to Providers
     *
     * @access    private
     * @param    project id and checkstamp
     * @return    contents
     */
    function hourlyProjectsNotify()
    {
        //Load Models
        $this->load->model('search_model');

        $prev_hour = date('j/n/Y H', get_est_time() - (60 * 60));

        $conditions = array('users.role_id' => '2', 'users.user_status' => '1', 'user_categories.user_categories !=' => '', 'users.project_notify' => 'Hourly');

        $users = $this->user_model->getUsersWithCategories($conditions);

        $prids = array();
        $i = 0;
        foreach ($users->result() as $user) {
            $cate = explode(",", $user->user_categories);
            //Get projects by categories
            foreach ($cate as $cat) {
                $cond = array('categories.id' => $cat);
                $res = $this->skills_model->getCategories($cond);
                $row = $res->row();
                $cname = $row->category_name;
                $like = array('projects.project_categories' => $cname);
                $conditions2 = array("FROM_UNIXTIME( projects.created, '%e/%c/%Y %H' ) = " => $prev_hour, 'projects.project_status' => '0');
                $projects = $this->search_model->getProjects($conditions2, 'projects.id', $like);
                //Get projects
                foreach ($projects->result() as $prid) {
                    $prids[$i] = $prid->id;
                    $i++;
                }
            }
            //Check if projects are available to send notifications
            if (count($prids) > 0) {
                $prids1 = array_unique($prids);
                $mailSubject = $this->config->item('site_title') . " Project Notice";
                $mailContent = "The following " . count($prids1) . " projects were recently added to " . $this->config->item('site_title') . " and match your expertise:<br><br>";
                foreach ($prids as $prj) {
                    $condition3 = array('projects.id' => $prj);
                    $mpr = $this->skills_model->getProjects($condition3);
                    $prj = $mpr->row();
                    $mailContent .= $prj->project_name . " (Posted by " . $prj->user_name . ", " . get_datetime($prj->created) . ", Job type:" . $prj->project_categories . ")" . "<br>" . site_url('project/view/' . $prj->id) . "<br><br>";
                }
                //Send mail
                $toEmail = $user->email;
                $fromEmail = $this->config->item('site_admin_mail');
                $this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);
            }
        }
    }//Function hourlyProjectsNotify End

    // -----------------------------------------------------------------------------------------------------------------
    function selProvider()
    {

        //Load Language
        $this->lang->load('enduser/pickProvider', $this->config->item('language_code'));
        if ($this->uri->segment(3, 0)) {
            $bidid = $this->uri->segment(3, 0);
            $conditions = array('bids.id' => $bidid);
            $up = $this->skills_model->awardProject($conditions);
            if ($up == 1) {
                //Load Model For Mail
                $this->load->model('email_model');
                $bidres = $this->skills_model->getProjectByBid(array('bids.id' => $bidid));
                $bidres = $bidres->row();

                //Get all user post bids 
                $condition = array('bids.project_id' => $bidres->id, 'bids.user_id !=' => $bidres->programmer_id);
                $bids = $this->skills_model->getBids($condition);
                foreach ($bids->result() as $bids) {
                    $user_condition = array('users.id' => $bids->user_id);
                    $users = $this->user_model->getUsers($user_condition);
                    $users = $users->row();

                    //Send Mail
                    $conditionUserMail = array('email_templates.type' => 'project_end');
                    $result = $this->email_model->getEmailSettings($conditionUserMail);
                    $rowUserMailConent = $result->row();
                    $splVars = array("!projectname" => $bidres->project_name, "!sitetitle" => site_url(), "!contact_url" => site_url('contact'));
                    $mailSubject = strtr($rowUserMailConent->mail_subject, $splVars);
                    $mailContent = strtr($rowUserMailConent->mail_body, $splVars);
                    $toEmail = $users->email;
                    $fromEmail = $this->config->item('site_admin_mail');
                    $this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);
                }
                //Update the notification status for the proejct to zero
                $updateKey = array('projects.id' => $bidres->id);
                $updateData['notification_status'] = '0';
                $this->skills_model->updateProjects(NULL, $updateData, $updateKey);

                //Send Mail
                $conditionUserMail = array('email_templates.type' => 'awardBid');
                $result = $this->email_model->getEmailSettings($conditionUserMail);
                $rowUserMailConent = $result->row();
                $splVars = array("!project_title" => $bidres->project_name, "!bid_url" => site_url('project/acceptProject/' . $bidres->id . "/" . $bidres->checkstamp), "!deny_url" => site_url('project/denyProject/' . $bidres->id . "/" . $bidres->checkstamp), "!contact_url" => site_url('contact'));
                $mailSubject = strtr($rowUserMailConent->mail_subject, $splVars);
                $mailContent = strtr($rowUserMailConent->mail_body, $splVars);
                $toEmail = $bidres->email;
                $fromEmail = $this->config->item('site_admin_mail');
                $this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);

                $resuser = $this->user_model->getUsers(array('users.id' => $this->loggedInUser->id));
                $tuserdetails = $resuser->row();
                //Notification message
                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('success', $this->lang->line('You have successfully awarded the project')));
                redirect('/project/view/' . $bidres->id);
            }
        }

    }


    /**
     * Buyer cencel the proejct only for open proejcts
     *
     * @access    private
     * @param    nil
     * @return    void
     */
    function cancelProjectUpdate(){
        if($this->uri->segment(3, 0)){
            $projectid = $this->uri->segment(3, 0);
            $updatekey = array('projects.id' => $projectid);

            //Get the cancelled proejcts details
            $condition = array('projects.id' => $projectid);
            $projects = $this->skills_model->getProjects($condition);
            $this->outputData['projects'] = $projects;
            $projects = $projects->row();

            //Set the proejct status as cancel made by buyer
            $updateData = array('projects.project_status' => '3');
            $projects = $this->skills_model->updateProjects(NULL, $updateData, $updatekey);
            $data = array('status'=>'success','message'=>$this->lang->line('Delete project successful'));
            echo json_encode($data);exit;
        }
    }

    function restoreProjectUpdate(){
        if($this->uri->segment(3, 0)){
            $projectid = $this->uri->segment(3, 0);
            $updatekey = array('projects.id' => $projectid);

            //Get the cancelled proejcts details
            $condition = array('projects.id' => $projectid);
            $projects = $this->skills_model->getProjects($condition);
            $this->outputData['projects'] = $projects;
            $projects = $projects->row();

            //Set the proejct status as cancel made by buyer
            $updateData = array('projects.project_status' => '0');
            $projects = $this->skills_model->updateProjects(NULL, $updateData, $updatekey);
            $data = array('status'=>'success','message'=>$this->lang->line('Restore project successful'));
            echo json_encode($data);exit;
        }
    }
    function reloadStatusProject(){
        // load language
         $this->lang->load('enduser/viewProject', $this->config->item('language_code'));
        //Conditions list project buyer tạo ra
        if ($this->loggedInUser) {
            $buyer_id = $this->loggedInUser->id;
            //pagination limit
            $page_rows1 = $this->config->item('listing_limit');

            $limit1[0] = $page_rows1;
            $limit1[1] = '0';
            $page = $this->uri->segment(3, '0');

        if (isset($page) === false or empty($page)) {
            $page = '1';
        }


        $page_rows = $this->config->item('listing_limit');

        $max = array($page_rows, ($page - 1) * $page_rows);
            $order = array('projects.id', 'desc');
            $conditions = array('projects.creator_id' => $buyer_id, 'projects.project_status !=' => '2');
            $this->outputData['myProjects'] = $this->skills_model->getProjects($conditions, NULL, NULL, $max, $order);
            $created = $this->skills_model->getProjects($conditions);
            //Pagination
            $this->load->library('pagination');
            $config['base_url'] = site_url('project/reloadStatusProject/');
            $config['total_rows'] = $created->num_rows();
            $config['per_page'] = $page_rows;
            $config['cur_page'] = $page;
            $this->pagination->initialize($config);
            $this->outputData['pagination'] = $this->pagination->create_links(false, 'project');
        }
        
        $this->load->view("project/reloadStatusProject",$this->outputData);
    }


    function cancelProject()
    {
        if ($this->uri->segment(3, 0)) {

            $projectid = $this->uri->segment(3, 0);
            $updatekey = array('projects.id' => $projectid);

            //Get the cancelled proejcts details
            $condition = array('projects.id' => $projectid);
            $projects = $this->skills_model->getProjects($condition);
            $this->outputData['projects'] = $projects;
            $projects = $projects->row();

            if ($this->input->post('delete')) {
                //Set the proejct status as cancel made by buyer
                $updateData = array('projects.project_status' => '3');
                $projects = $this->skills_model->updateProjects(NULL, $updateData, $updatekey);

                //Get all bid post users to the particular project
                $condition = array('projects.id' => $projectid);
                $getBids = $this->skills_model->getBids($condition);
                if ($getBids->num_rows() > 0) {
                    foreach ($getBids->result() as $user) {
                        $user_condition = array('users.id' => $user->user_id);
                        $usersList = $this->user_model->getUsers($user_condition);
                        $usersList = $usersList->row();
                        //Get projects details
                        $condition = array('projects.id' => $this->uri->segment(3, 0));
                        $projects = $this->skills_model->getProjects($condition);
                        $projects = $projects->row();
                        //Send Mail to project creator
                        $conditionUserMail = array('email_templates.type' => 'project_cancel');
                        $result = $this->email_model->getEmailSettings($conditionUserMail);
                        $rowUserMailConent = $result->row();
                        $splVars = array("!projectname" => '<a href="' . site_url('project/view/' . $projects->id) . '">' . $projects->project_name . '</a>', "!username" => $usersList->user_name, "!contact_url" => site_url('contact'), "!site_url" => site_url(), '!site_name' => $this->config->item('site_title'), "!projectid" => $projects->id, "!creatorname" => $this->loggedInUser->user_name);

                        $mailSubject = strtr($rowUserMailConent->mail_subject, $splVars);
                        $mailContent = strtr($rowUserMailConent->mail_body, $splVars);
                        $toEmail = $this->loggedInUser->email;
                        $fromEmail = $this->config->item('site_admin_mail');
                        $this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);
                    }
                }

                //Get projects details
                $condition = array('projects.id' => $this->uri->segment(3, 0));
                $projects = $this->skills_model->getProjects($condition);
                $projects = $projects->row();
                //Send Mail to project creator
                $conditionUserMail = array('email_templates.type' => 'project_cancel');
                $result = $this->email_model->getEmailSettings($conditionUserMail);
                $rowUserMailConent = $result->row();
                $splVars = array("!projectname" => '<a href="' . site_url('project/view/' . $projects->id) . '">' . $projects->project_name . '</a>', "!username" => $this->loggedInUser->user_name, "!contact_url" => site_url('contact'), "!site_url" => site_url(), '!site_name' => $this->config->item('site_title'), "!projectid" => $projects->id, "!creatorname" => $this->loggedInUser->user_name);
                $mailSubject = strtr($rowUserMailConent->mail_subject, $splVars);
                $mailContent = strtr($rowUserMailConent->mail_body, $splVars);
                $toEmail = $this->loggedInUser->email;
                $fromEmail = $this->config->item('site_admin_mail');
                $this->email_model->sendHtmlMail($toEmail, $fromEmail, $mailSubject, $mailContent);
                redirect('buyer/viewMyProjects');
            } else if ($this->input->post('viewProject')) {
                redirect('buyer/viewMyProjects');
            } else {
                $this->load->view('project/deleteProject', $this->outputData);


            }
        }

    }

    //check max value
    function _maxvalcheck()
    {
        $min = $this->input->post('budget_min');
        $max = $this->input->post('budget_max');
        if ($min < $max) {
            return true;
        } else {
            $this->form_validation->set_message('_maxvalcheck', $this->lang->line('max_min_check'));
            return false;
        }


    }

    function _maxvalcheckcat()
    {

        $max = $this->input->post('categories');
        if (count($max) < 6) {
            return true;
        } else {
            $this->form_validation->set_message('categories[]', $this->lang->line('Job Type: (Make up to 5 selections.)'));
            return false;

        }
    }

    function getRequestCategories(){ echo $_GET['group_id'];exit;
            if($this->input->get('group_id')){
            $condition = array('group_id' => $this->input->get('group_id'));
            $data = $this->skills_model->getCategories($condition,array('categories.category_name'));
            echo json_encode($data->result());exit;
        }
    }
    function listFreelancerBid(){
        $project_id = $this->uri->segment(3);
        $this->lang->load('enduser/viewProject', $this->config->item('language_code'));
        $this->lang->load('enduser/createBids', $this->config->item('language_code'));
        if($project_id){
            $fields = array('bids.bid_amount','bids.bid_days','users.user_name','users.logo');
            $conditions = array('projects.id' => $project_id);
            $conditions1 = array('projects.id' => $project_id,'bids.is_deleted' => 0);
            $orderby = array('bids.bid_time','desc');
            $this->outputData['projects'] = $this->skills_model->getProjects($conditions);
            $this->outputData['listBid'] = $this->skills_model->getBids($conditions1,$fields,null,null,$orderby);

        }
        $this->load->view('project/listFreelancerBid',$this->outputData);
    }
    function listRecommendDeveloper(){
        $project_id = $this->uri->segment(3);
        if($project_id){
            $fields = array('bids.bid_amount','bids.bid_days','users.user_name','users.logo');
            $conditions = array('projects.id' => $project_id);
           // $conditions1 = array('projects.id' => $project_id,'bids.is_deleted' => 0);
            $orderby = array('bids.bid_time','desc');
            $this->outputData['pr'] = $this->skills_model->getProjects($conditions);     
        }
        $this->load->view('project/listFreelancerRecommend',$this->outputData);
    }
    function createMilestone(){
        //load language
        $this->lang->load('enduser/milestone',$this->config->item('language_code'));
        $this->lang->load('enduser/common',$this->config->item('language_code'));

        //load model
        $this->load->model('milestone_model');
        $this->outputData['cate_milestones'] = $this->milestone_model->getCateMilestone();

        if($this->input->post('milestone_cateId',TRUE) && $this->input->post('project_id',TRUE)){
            $conditions = array('category_id' => $this->input->post('milestone_cateId',TRUE),'milestones.is_deleted' => 0);
            $fields = array('milestones.title as name','milestones.return_fee as fee','milestones.order','milestones.order');
            $result = $this->milestone_model->getMilestoneCate($conditions,$fields);
            $projects_id = $this->input->post('project_id',TRUE);
            $category_id = $this->input->post('milestone_cateId',TRUE);
            //get milestones by milestones categories
            if($result->num_rows() > 0){
                $insertData = $result->result_array();
                $this->milestone_model->insertCustomMilestone($insertData,$projects_id,$category_id,1);
                echo json_encode(array('status'=>'success'));exit;
            }else{
                echo json_encode(array('status' => 'error'));exit;
            }
        }else{
            echo json_encode(array('status' => 'error'));exit;
        }


        $this->load->view('project/createMilestone',$this->outputData);

    }
    /**
     * ajax get categories by group_id
     */
	function ajaxGetCategories(){
		if($this->input->post('group_id')){
			$condition = array('group_id' => $this->input->post('group_id'));
			$data = $this->skills_model->getCategories($condition,"categories.id, categories.category_name");
			echo json_encode($data->result_array());
			die;
		}elseif ($this->input->post('ids')){
			$ids = explode(',',$this->input->post('ids'));
			$data = $this->skills_model->getCategories(NULL,"categories.id, categories.category_name", $ids);
			echo json_encode($data->result_array());
			die;
		}
	}

    function editMilestone(){
        //load language
        $this->lang->load('enduser/milestone',$this->config->item('language_code'));
        $this->lang->load('enduser/common',$this->config->item('language_code'));

        $this->load->model('milestone_model');
        $this->load->library('form_validation');
        if($this->input->post('project_id',TRUE)){
            $conditions = array('projects_id' => $this->input->post('project_id',TRUE));
            $fields = array('projects_milestones.name','projects_milestones.status','projects_milestones.fee','projects_milestones.id');
            $this->outputData['rows_projects_milestones'] = $this->milestone_model->getProjectsMilestone($conditions,$fields);
            $this->outputData['project_id'] = $this->input->post('project_id',TRUE);

            $conditions2 = array('projects.id' => $this->outputData['project_id']);
            $this->outputData['project'] = $this->skills_model->getProjects($conditions2)->row();

            $this->outputData['sum_milestone'] = $this->milestone_model->sumMilestone($conditions);



            $conditions_bid = array('bids.project_id' => $this->outputData['project_id'],'bids.user_id' => $this->outputData['project']->programmer_id);
            $fields_bid = array('bids.bid_amount','bids.escrow_flag');
            $this->outputData['bids'] = $this->skills_model->getBids($conditions_bid,$fields_bid)->row();

            $this->outputData['sum_bid'] = $this->outputData['bids']->bid_amount - $this->outputData['bids']->escrow_flag;

            $this->load->view('project/editMilestone',$this->outputData);
        }

    }
    function loadMilestone(){
        if($this->input->post('value',TRUE)){
            $this->load->model('milestone_model');
            $condition = array('milestones.category_id' => $this->input->post('value',TRUE),'milestones.is_deleted' => 0);
            $field = array('milestones.title','milestones.return_fee');
            $result = $this->milestone_model->getMilestoneCate($condition,$field)->result();
            echo json_encode(array('status' => 'success','data' => $result));exit;
        }else{
            echo json_encode(array('status' => 'error'));exit;
        }
    }
    function createCustomMilestone(){
        $this->lang->load('enduser/formValidation',$this->config->item('language_code'));
        $this->lang->load('enduser/common',$this->config->item('language_code'));
        $this->lang->load('enduser/milestone',$this->config->item('language_code'));
        // load language


        if($this->input->post('projects_id',TRUE) ){
            $this->load->model('milestone_model');
            $projects_id = $this->input->post('projects_id',TRUE);

            $conditions = array('projects.id' => $projects_id);
            $fields = array('projects.programmer_id');
            $result = $this->skills_model->getProjects($conditions,$fields)->row();
            // get Programmer_id of Project

            $conditions = array('projects.id' => $projects_id,'users.id' => $result->programmer_id);
            $fields = array('bids.bid_amount','bids.escrow_flag');
            $bids = $this->skills_model->getBids($conditions,$fields)->row();
            //get bid amount of Project


            $data = json_decode($this->input->post('data',TRUE));
            $fee = json_decode($this->input->post('fee',TRUE));
            $i = 0;
            foreach($data as $item){
                $i++;
                if($item->value == "")
                {
                    echo json_encode(array('status' => 'error','message' => $this->lang->line('Name Milestone')." ".$this->lang->line('required')));exit;
                }
                $insertData[$i]['name'] = $item->value;
            }
            $j = 0;
            $total = 0;
            foreach($fee as $item){
                $j++;
                if(!is_numeric($item->value))
                {
                    echo json_encode(array('status'=>'error','message' => "Giá trị milestone ".$this->lang->line('numeric')));exit;
                }
                $insertData[$j]['fee'] = $item->value;
                $total += $insertData[$j]['fee'];
                $insertData[$j]['order'] = $j;
            }
            $milestone_total = $bids->bid_amount - $bids->escrow_flag;
            if(($total < $milestone_total) || ($total > $milestone_total)){
                echo json_encode(array('status' => 'error','message' => "Tổng tiền phải bằng số tiền bid"));exit;
            }

            if(!empty($insertData)){
                $this->milestone_model->insertCustomMilestone($insertData,$projects_id);
                echo json_encode(array('status'=>'success'));exit;
            }else{
                echo json_encode(array('status'=>'error'));exit;
            }
        }else{
            echo json_encode(array('status'=>'error'));exit;
        }
    }
    function completeProject(){
        if($this->input->post('project_id',TRUE)){
            $this->load->model('milestone_model');
            $conditions = array('projects.id' => $this->input->post('project_id',TRUE));
            $fields = array('projects_milestones.status','projects_milestones.fee');

            $result = $this->milestone_model->getProjectsMilestone($conditions,$fields);
            if($result->num_rows() > 0){
                $total = 0;
                foreach($result->result() as $item){
                    if($item->status != 2){
                        echo json_encode(array('status' => 'error','message' => 'Milestone chưa hoàn thành'));exit;
                    }
                    $total += $item->fee;
                }
                $conditions2 = array('projects.id' => $this->input->post('project_id',TRUE));
                $fields2 = array('projects.programmer_id');
                $this->outputData['projects'] = $this->skills_model->getProjects($conditions2,$fields2)->row();
                // get programmer_id project

                $conditions3 = array('projects.id' => $this->input->post('project_id',TRUE),'user_id' => $this->outputData['projects']->programmer_id);
                $fields3 = array('bids.bid_amount','bids.escrow_flag');
                $bids = $this->skills_model->getBids($conditions3,$fields3)->row();
                //get bids project by programmer_id
                $sum_bid = $bids->bid_amount - $bids->escrow_flag;
                if($total < $sum_bid){
                    echo json_encode(array('status' => 'error'));exit;
                }

                $updateData['project_status'] = '2';
                $this->skills_model->updateProjects($this->input->post('project_id',TRUE),$updateData);
                echo json_encode(array('status'=>'success'));exit;
            }
        }else{
            echo json_encode(array('status' => 'error'));exit;
        }
    }
    function devRequestMilestone(){
        if($this->input->post('milestone_id',TRUE)){
            $this->load->model('milestone_model');

            $conditions = array('projects_milestones.id' => $this->input->post('milestone_id',TRUE));
            $fields = array('projects_milestones.projects_id');
            $id_project = $this->milestone_model->getProjectsMilestone($conditions,$fields)->row();
            $updateData = array('projects_milestones.status' => 1);
            //update status milestone  = 1

            $conditions2 = array('projects.id' => $id_project->projects_id);
            $fields2 = array('projects.creator_id');
            $to_id = $this->skills_model->getProjects($conditions2,$fields2)->row();
            // get project creator id

            if(($this->input->post('message',TRUE) != "") && (isset($this->loggedInUser->id))){
                $insertData['from_id'] = $this->loggedInUser->id;
                $insertData['to_id'] = $to_id->creator_id;
                $insertData['message'] = $this->input->post('message',TRUE);
                $insertData['project_id'] = $id_project->projects_id;
                $insertData['created'] = time();
                $insertData['milestone_id'] = $this->input->post('milestone_id',TRUE);
                $insertData['type'] = 3;

                $this->messages_model->postMessage($insertData);
            }
            $this->milestone_model->updateMilestone(0,$updateData,$conditions);
            echo json_encode(array('status' => 'success','project_id' => $id_project->projects_id));exit;
        }
    }
    function withdrawDevRequestMilestone(){
        if($this->input->post('milestone_id',TRUE)){
            $this->load->model('milestone_model');

            $conditions = array('projects_milestones.id' => $this->input->post('milestone_id',TRUE));
            $fields = array('projects_milestones.projects_id');
            $id_project = $this->milestone_model->getProjectsMilestone($conditions,$fields)->row();
            $updateData = array('projects_milestones.status' => 0);
            $this->milestone_model->updateMilestone(0,$updateData,$conditions);
            //update status milestone  = 0

            $conditions2 = array('projects.id' => $id_project->projects_id);
            $fields2 = array('projects.creator_id');
            $to_id = $this->skills_model->getProjects($conditions2,$fields2)->row();
            // get project creator id

            if(($this->input->post('message',TRUE) != "") && (isset($this->loggedInUser->id))){
                $insertData['from_id'] = $this->loggedInUser->id;
                $insertData['to_id'] = $to_id->creator_id;
                $insertData['message'] = $this->input->post('message',TRUE);
                $insertData['project_id'] = $id_project->projects_id;
                $insertData['created'] = time();
                $insertData['milestone_id'] = $this->input->post('milestone_id',TRUE);
                $insertData['type'] = 4;

                $this->messages_model->postMessage($insertData);
            }

            echo json_encode(array('status' => 'success','project_id' => $id_project->projects_id));exit;
        }
    }
    function deniedDevRequestMilestone(){
        if($this->input->post('milestone_id',TRUE)){
            $this->load->model('milestone_model');

            $conditions = array('projects_milestones.id' => $this->input->post('milestone_id',TRUE));
            $fields = array('projects_milestones.projects_id');
            $id_project = $this->milestone_model->getProjectsMilestone($conditions,$fields)->row();
            $updateData = array('projects_milestones.status' => 0);
            $this->milestone_model->updateMilestone(0,$updateData,$conditions);
            //update status milestone  = 0

            $conditions2 = array('projects.id' => $id_project->projects_id);
            $fields2 = array('projects.creator_id','projects.programmer_id');
            $to_id = $this->skills_model->getProjects($conditions2,$fields2)->row();
            // get project creator id

            if(($this->input->post('message',TRUE) != "") && (isset($this->loggedInUser->id))){
                $insertData['from_id'] = $this->loggedInUser->id;
                $insertData['to_id'] = $to_id->programmer_id;
                $insertData['message'] = $this->input->post('message',TRUE);
                $insertData['project_id'] = $id_project->projects_id;
                $insertData['created'] = time();
                $insertData['milestone_id'] = $this->input->post('milestone_id',TRUE);
                $insertData['type'] = 4;

                $this->messages_model->postMessage($insertData);
            }

            echo json_encode(array('status' => 'success','project_id' => $id_project->projects_id));exit;
        }
    }
    function completeOneMilestone(){
        if($this->input->post('milestone_id',TRUE)){
            $this->load->model('milestone_model');

            $conditions = array('projects_milestones.id' => $this->input->post('milestone_id',TRUE));
            $fields = array('projects_milestones.projects_id','projects_milestones.fee');
            $id_project = $this->milestone_model->getProjectsMilestone($conditions,$fields)->row();
            $updateData = array('projects_milestones.status' => 2);
            $this->milestone_model->updateMilestone(0,$updateData,$conditions);
            //update status milestone  = 0

            $conditions2 = array('projects.id' => $id_project->projects_id);
            $fields2 = array('projects.creator_id','projects.programmer_id');
            $to_id = $this->skills_model->getProjects($conditions2,$fields2)->row();
            // get project creator id

            if(($this->input->post('message',TRUE) != "") && (isset($this->loggedInUser->id))){
                $insertData['from_id'] = $this->loggedInUser->id;
                $insertData['to_id'] = $to_id->programmer_id;
                $insertData['message'] = $this->input->post('message',TRUE);
                $insertData['project_id'] = $id_project->projects_id;
                $insertData['created'] = time();
                $insertData['milestone_id'] = $this->input->post('milestone_id',TRUE);
                $insertData['type'] = 5;

                $this->messages_model->postMessage($insertData);
            }
                // gửi message
                $this->load->helper('transaction');
                $balance = getFrozenBalance($this->loggedInUser->id);

                if( (isset($balance) == TRUE ) && ( $balance >= $id_project->fee ) ){
                    debitFrozen($to_id->creator_id,$id_project->fee);
                    updateFrozen($to_id->programmer_id,$id_project->fee);
                    $insertData['from_id'] = $this->loggedInUser->id;
                    $insertData['to_id'] = $to_id->programmer_id;
                    $insertData['message'] = "";
                    $insertData['project_id'] = $id_project->projects_id;
                    $insertData['created'] = time();
                    $insertData['milestone_id'] = $this->input->post('milestone_id',TRUE);
                    $insertData['type'] = 7;

                    $this->messages_model->postMessage($insertData);
                    // gửi message thông báo nhận được tiền.

                    $transactionData['creator_id'] = $this->loggedInUser->id;
                    $transactionData['buyer_id'] = $this->loggedInUser->id;
                    $transactionData['provider_id'] = $to_id->programmer_id;
                    $transactionData['transaction_time'] = time();
                    $transactionData['amount'] = $id_project->fee;
                    $transactionData['status'] = "Complete";
                    $transactionData['project_id'] = $id_project->projects_id;
                    $transactionData['milestones_id'] = $this->input->post('milestone_id',TRUE);

                    $this->transaction_model->addTransaction($transactionData);
                    // add transaction.

                }else{
                    echo json_encode(array('status' => 'error','project_id' => $id_project->projects_id));exit;
                }
            echo json_encode(array('status' => 'success','project_id' => $id_project->projects_id));exit;
        }
    }
    // end function completeOneMilestone
    function removeOneMilestone(){
        $id_milestone = $this->uri->segment(3,'0');
        if($id_milestone != 0){
            $this->load->model('milestone_model');
            $condition = array('projects_milestones.id' => $id_milestone);
            $fields = array('projects_milestones.status','projects_milestones.projects_id');

            $status = $this->milestone_model->getProjectsMilestone($condition,$fields)->row();

            if($status->status == 0){
                if($this->milestone_model->removeOneMilestone($condition))
                    redirect('project/view/'.$status->projects_id);
            }
        }
    }
    function updateMilestone(){
        $this->lang->load('enduser/formValidation',$this->config->item('language_code'));
        $this->lang->load('enduser/common',$this->config->item('language_code'));
        $this->lang->load('enduser/milestone',$this->config->item('language_code'));
        // load language


        if($this->input->post('projects_id',TRUE) ){
            $this->load->model('milestone_model');
            $projects_id = $this->input->post('projects_id',TRUE);

            $conditions = array('projects.id' => $projects_id);
            $fields = array('projects.programmer_id');
            $result = $this->skills_model->getProjects($conditions,$fields)->row();
            // get Programmer_id of Project

            $conditions = array('projects.id' => $projects_id,'user_id' => $result->programmer_id);
            $fields = array('bids.bid_amount');
            $bids = $this->skills_model->getBids($conditions,$fields)->row();
            //get bid amount of Project

            $conditions = array('projects_id' => $projects_id);
            $fields = array('bids.bid_amount');
            $sum_milestone = $this->milestone_model->sumMilestone($conditions);
            // lấy tổng giá trị milestone hiện có

            $data = json_decode($this->input->post('data',TRUE));
            $fee = json_decode($this->input->post('fee',TRUE));
            $i = 0;
            foreach($data as $item){
                $i++;
                if($item->value == "")
                {
                    echo json_encode(array('status' => 'error','message' => $this->lang->line('Name Milestone')." ".$this->lang->line('required')));exit;
                }
                $insertData[$i]['name'] = $item->value;
            }
            $j = 0;
            $total = 0;
            foreach($fee as $item){
                $j++;
                if(!is_numeric($item->value))
                {
                    echo json_encode(array('status'=>'error','message' => $this->lang->line('numeric')));exit;
                }
                $insertData[$j]['fee'] = $item->value;
                $total += $insertData[$j]['fee'];
                $insertData[$j]['order'] = $j;
            }

            if(($total > ( $bids->bid_amount - $sum_milestone->fee ) ) ){
                echo json_encode(array('status' => 'error','message' => "Tổng tiền phải bằng số tiền bid"));exit;
            }

            if(!empty($insertData)){
                $this->milestone_model->insertCustomMilestone($insertData,$projects_id);
                echo json_encode(array('status'=>'success'));exit;
            }else{
                echo json_encode(array('status'=>'error'));exit;
            }
        }else{
            echo json_encode(array('status'=>'error'));exit;
        }
    }
    function bonusMilestone(){
        if($this->input->post('milestone_id',TRUE)){
            $this->load->model('milestone_model');

            $conditions = array('projects_milestones.id' => $this->input->post('milestone_id',TRUE));
            $fields = array('projects_milestones.projects_id','projects_milestones.fee');
            $id_project = $this->milestone_model->getProjectsMilestone($conditions,$fields)->row();

            $conditions2 = array('projects.id' => $id_project->projects_id);
            $fields2 = array('projects.creator_id','projects.programmer_id');
            $to_id = $this->skills_model->getProjects($conditions2,$fields2)->row();
            // get project creator_id and programmer_id

            if(($this->input->post('message',TRUE) != "") && (isset($this->loggedInUser->id))){
                $this->load->helper('transaction');
                $balance = getAmountBalance($this->loggedInUser->id);
                if($this->input->post('fee',TRUE) && is_numeric($this->input->post('fee',TRUE)) ){
                    $fee = $this->input->post('fee',TRUE);
                    if( (isset($balance) == TRUE ) && ( $balance >= $fee ) ){
                        debitAmount($this->loggedInUser->id,$fee);
                        updateFrozen($to_id->programmer_id,$fee);
                        $insertData['from_id'] = $this->loggedInUser->id;
                        $insertData['to_id'] = $to_id->programmer_id;
                        $insertData['message'] = $this->input->post('message',TRUE);
                        $insertData['project_id'] = $id_project->projects_id;
                        $insertData['created'] = time();
                        $insertData['milestone_id'] = $this->input->post('milestone_id',TRUE);
                        $insertData['type'] = 8;

                        $this->messages_model->postMessage($insertData);
                        // gui message

                        $transactionData['creator_id'] = $this->loggedInUser->id;
                        $transactionData['buyer_id'] = $this->loggedInUser->id;
                        $transactionData['provider_id'] = $to_id->programmer_id;
                        $transactionData['transaction_time'] = time();
                        $transactionData['amount'] = $fee;
                        $transactionData['status'] = "Complete";
                        $transactionData['project_id'] = $id_project->projects_id;
                        $transactionData['milestones_id'] = $this->input->post('milestone_id',TRUE);

                        $this->transaction_model->addTransaction($transactionData);
                    }else{
                        echo json_encode(array('status' => 'error','project_id' => $id_project->projects_id));exit;
                    }
                }
                echo json_encode(array('status' => 'success','project_id' => $id_project->projects_id));exit;
            }
        }
    }
    function uploadFile(){
        $title = json_decode($this->input->post('title',TRUE));
        $description = json_decode($this->input->post('description',TRUE));


        //print_r($title);exit;
        //print_r($_FILES['file']);exit;
        //print_r($this->input->post('projects_id',TRUE));exit;
        $this->load->library('upload');
        $file_ary = $_FILES;
        //print_r($file_ary);exit;
        $file_count = count($_FILES['file']['name']);
        $array_title = array();

        if($this->input->post('projects_id',TRUE)){
            $conditions = array('projects.id' => $this->input->post('projects_id',TRUE));
            $fields = array('projects.programmer_id');
            $result = $this->skills_model->getProjects($conditions,$fields)->row();
            // get Programmer_id of Project


            for($i = 0;$i < count($title);$i++){
                $array_title[$i]['title'] = $title[$i]->value;
                $array_title[$i]['description'] = $description[$i]->value;
            }
            //print_r($array_title);exit;

            for ($i=0; $i<$file_count; $i++) {
                $_FILES['file']['name']= $file_ary['file']['name'][$i];
                $_FILES['file']['type']= $file_ary['file']['type'][$i];
                $_FILES['file']['tmp_name']= $file_ary['file']['tmp_name'][$i];
                $_FILES['file']['error']= $file_ary['file']['error'][$i];
                $_FILES['file']['size']= $file_ary['file']['size'][$i];

                $this->upload->initialize($this->set_upload_options());
                //$this->upload->do_upload();
                if($this->upload->do_upload('file')){
                    $upload_data = $this->upload->data();
                    $insertData['user_id'] = $this->loggedInUser->id;
                    $insertData['to_id'] = $result->programmer_id;
                    $insertData['created'] = time();
                    $insertData['delete'] = 0;
                    $insertData['description'] = $description[$i]->value;
                    $insertData['title'] = $title[$i]->value;
                    $insertData['file_size'] = $upload_data['file_size'];
                    $insertData['file_type'] = $upload_data['file_type'];
                    $insertData['original_name'] = $upload_data['orig_name'];
                    $insertData['path'] = "files/".$upload_data['file_name'];
                    $insertData['projects_id'] = $this->input->post('projects_id',TRUE);

                    $this->file_model->postFile($insertData);
                }else{
                    $upload_error = $this->upload->display_errors();
                    print_r($upload_error);exit;
                }
            }

        }

    }
    private function set_upload_options()
    {
        //  upload an image options
        $config = array();
        $config['upload_path'] = 'files/project_attachment/files/';
        $config['allowed_types'] = 'jpeg|jpg|png|gif|JPEG|JPG|PNG|GIF|zip|ZIP|RAR|rar|doc|DOC|txt|TXT|xlsx|XLSX|xls|XLS|ppt|PPT|pdf|PDF|docx|DOCX|PPTX|pptx|CSV|csv';
        $config['max_size']      = '0';
        $config['overwrite']     = FALSE;


        return $config;
    }
    function listDownloadFile(){
        $this->outputData['project_id'] = $this->input->post('project_id',TRUE);
        if($this->outputData['project_id']){
            $conditions = array('projects_id' => $this->outputData['project_id'],'delete' => 0);
            $fields = array('title','description','path','id');
            $this->outputData['listDownloadFile'] = $this->file_model->getFile($conditions,$fields);
        }
        $this->load->view('project/listDownloadFile',$this->outputData);
    }
    function DownloadFile(){
        $id_file = $this->uri->segment(3,'0');
        if($id_file){
            $conditions = array('id' => $id_file,'delete' => 0);
            $this->outputData['file'] = $this->file_model->getFile($conditions)->row();
        }
        $this->load->view('project/DownloadFile',$this->outputData);
    }
    function deleteFile(){
        $id_file = $this->input->post('file_id',TRUE);
        if($id_file){
            $conditions = array('delete' => 1);
            $this->outputData['file'] = $this->file_model->updateFile($id_file,$conditions);
        }
        //$this->load->view('project/DownloadFile',$this->outputData);
    }
    
    function getChildCategory(){
    	$id_category = $this->input->post('id_category',TRUE);
    	if($id_category){
    		$conditions = array('groups.is_deleted' => 0,'groups.parent_id' => $id_category);
    		$fields = array('groups.id','groups.group_name');
    		$childCategory = $this->skills_model->getGroup($conditions,$fields);
    		echo json_encode(array('status' => 'success','data' => $childCategory->result()));
    	}else{
    		echo json_encode(array('status' => 'error'));
    	}
    }
    
    function ajaxGetCountries(){
    	$countCountry = $this->skills_model->getCountries()->num_rows();
    	$countries = $this->skills_model->getCountries(NULL, NULL, NULL, array('0' => $countCountry, '1' => 30))->result_array();
    	echo json_encode($countries); die;
    }
    function part1(){
        $id_product = $this->uri->segment('3','0');
        if($id_product != 0){
            $conditions = array('projects.id' => $id_product);
            $this->outputData['projectDetail'] = $this->skills_model->getProjects($conditions);
            $conditions_skill = array('categories.is_deleted' => 0);
            $fields = array('categories.category_name','categories.id');
            $this->outputData['list_skills'] = $this->skills_model->getCategories($conditions_skill,$fields);


            $project = $this->outputData['projectDetail']->row();
            if(!empty($project->project_categories)){
                $result  = $this->user_model->getUsersByUserCategory($project->project_categories);
                if(count($result) > 0){
                    $this->outputData['userCate'] = $result;
                }else{
                    $this->outputData['userCate'] = 0;
                }
            }else{
                $this->outputData['userCate'] = 0;
            }


        }

        $this->load->view('project/part1',$this->outputData);
    }

    function contactFreelancer(){
        //language file
        $this->lang->load('enduser/buyerConfirm', $this->config->item('language_code'));
        $this->lang->load('enduser/loginUsers', $this->config->item('language_code'));
        $this->lang->load('enduser/formValidation', $this->config->item('language_code'));
        $this->lang->load('enduser/postMessage', $this->config->item('language_code'));
        $this->lang->load('enduser/userlist', $this->config->item('language_code'));

        // load helper
        $this->load->helper("bids");
       if( (isBuyer() || isProgrammer()) && isLoggedIn()){
        // nếu đã login
            $client_id = $this->loggedInUser->id;
            $freelancer_id = $this->uri->segment(3,'0');
            if($freelancer_id && is_numeric($freelancer_id)){
                $condition = array(
                    'projects.flag'             => '1',
                    'projects.project_status'   => '0',
                    'projects.is_deleted'       => 0,
                    'projects.creator_id'       => $client_id
                );
                $orderby = array('projects.created','desc');
                $projects = $this->skills_model->getProjects($condition,null,null,null,$orderby);
                if($projects->num_rows() > 0){
                    $this->outputData['projects'] = $projects;
                }
                $conditions = array(
                    'users.id'  => $freelancer_id,
                    'users.user_status' => '1'
                );
                $freelancer_info = $this->user_model->getUsers($conditions);
                if($freelancer_info->num_rows() > 0){
                    $this->outputData['freelancer_info'] = $freelancer_info;
                    // echo "<pre>";
                    // print_r($freelancer_info->row());
                    // echo "</pre>";exit;
                }
                $this->load->view('project/inviteFreelancerPage',$this->outputData);
            }

       }else{
        // nếu chưa login
            $freelancer_id = $this->uri->segment(3,'0');
            if($freelancer_id && is_numeric($freelancer_id)){
                $conditions = array(
                    'users.id'  => $freelancer_id,
                    'users.user_status' => '1'
                );
                $freelancer_info = $this->user_model->getUsers($conditions);
                 if($freelancer_info->num_rows() > 0)
                    $this->outputData['freelancer_info'] = $freelancer_info;

                $this->load->view("project/viewFreelancerWhenUnregister",$this->outputData);
            }
       }

    }


    function viewProjectAfterCreate(){
        // load helper
        $this->load->helper("bids");
        $this->load->helper("projectcases");
        $this->load->helper("file");

        // load lang
        $this->lang->load('enduser/viewProject', $this->config->item('language_code'));
        $this->lang->load('enduser/createBids', $this->config->item('language_code'));
        if (!isBuyer()) {
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You must be logged in as a buyer to view projects')));
            redirect('info');
        }

        if($this->uri->segment(3,'0') && is_numeric($this->uri->segment(3,'0'))){
            $this->load->helper("url");
            $projectID = $this->uri->segment(3,'0');

            $conditions = array('projects.id' => $projectID);
            $this->outputData['projectDetail'] = $this->skills_model->getProjects($conditions);
            if($this->outputData['projectDetail']->num_rows() > 0){
                if($this->session->userdata('user_id') != $this->outputData['projectDetail']->row()->creator_id)
                    // nếu không phải người tạo project thì hok được truy cập vào
                    redirect("home");

                $conditions_skill = array('categories.is_deleted' => 0);
                $fields = array('categories.category_name', 'categories.id');
                $this->outputData['list_skills'] = $this->skills_model->getCategories($conditions_skill, $fields);


                $project = $this->outputData['projectDetail']->row();

//
//                if (!empty($project->project_categories)) {
//                    $result = $this->user_model->getUsersByUserCategory($project->project_categories);
//                    if (count($result) > 0) {
//                        $this->outputData['userCate'] = $result;
//                    } else {
//                        //$this->outputData['userCate'] = 0;
//                        $conditions_user = array('users.user_status' => 1,'users.role_id' => 2);
//                        $order_user = array('users.user_rating','desc');
//                        $limit_user = array('10');
//                        //$this->outputData['userCate'] = $this->user_model->getUsers($conditions_user,null,$limit_user,$order_user);
//                        $userCate = $this->user_model->getUsers($conditions_user,null,$limit_user,$order_user);
//                        if($userCate->num_rows() > 0){
//                            $this->outputData['userCate'] = $userCate->result();
//                        }
//                    }
//                } else {
//                    $conditions_user = array('users.user_status' => 1,'users.role_id' => 2);
//                    $order_user = array('users.user_rating','desc');
//                    $limit_user = array('10');
//                    $userCate = $this->user_model->getUsers($conditions_user,null,$limit_user,$order_user);
//                    if($userCate->num_rows() > 0){
//                        $this->outputData['userCate'] = $userCate->result();
//                    }
//                }

                $conditions_invite = array('project_invitation.project_id' => $project->id,'project_invitation.sender_id' => $this->loggedInUser->id);
                $fields_invite = array('project_invitation.receiver_id');
                $listUserInvite = $this->user_model->getProgrammerInvitation($conditions_invite,$fields_invite);

                $array = array();
                if($listUserInvite->num_rows() > 0){
                    foreach($listUserInvite->result() as $item){
                        $this->outputData['UserInvited'][] = $item->receiver_id;
                    }
                }

                //print_r($array);exit;

                $conditions_user = array('users.user_status' => 1,'users.role_id' => 2);
                $order_user = array('users.id','random');
                $limit_user = array('8');
                $userCate = $this->user_model->getUsers($conditions_user,null,$limit_user,$order_user);
                if($userCate->num_rows() > 0){
                    $this->outputData['userCate'] = $userCate->result();
                }

                //print_r($this->outputData['userCate']);exit;


                // pagination
                $page_rows = 4;
                $page = $this->uri->segment(4, '0');
                if (isset($page) === false or empty($page)) {
                    $page = 1;
                }
                $limit = array($page_rows, ($page - 1) * $page_rows);


                $orderby = array('bids.bid_time', 'desc');
                // sort list dev
                if ($this->input->get('sort')) {
                    $this->outputData['sort'] = $this->input->get('sort');
                    $this->outputData['dir'] = $this->input->get('dir');
                    $orderby = array(
                        $this->input->get('sort'),
                        $this->input->get('dir')
                    );
                }

                // get detail project


                // get users match project
                $category_ids = explode(',', $project->project_categories);
                foreach ($category_ids as $item) {
                    $whereOr[] = 'FIND_IN_SET(' . $item . ', user_categories.user_categories)';
                }
                if (isset($whereOr) && count($whereOr) > 0) {
                    $strWhereOr = implode(' OR ', $whereOr);
                }
                $conditionOr = '(' . $strWhereOr . ')';
                $conditions = array('projects.id' => $projectID, 'bids.is_deleted' => 0);

                $this->outputData['listBid'] = $this->skills_model->getBids($conditions, null, null, $limit, $orderby, $conditionOr);
                /*
                            $orderby = array('bids.bid_time','desc');
                            $this->outputData['listBid'] = $this->skills_model->getBids($conditions,null,null,$limit,$orderby);

                */
                $re_num_rows = $this->skills_model->getBids($conditions);
                $this->outputData['numbids'] = getNumBid($projectID);
                $this->outputData['project_id'] = $projectID;

                // pagination continue
                $this->load->library('pagination');
                $config['base_url'] = site_url('project/viewProjectAfterCreate/' . $projectID . '/');
                $config['total_rows'] = $re_num_rows->num_rows();
                $config['per_page'] = $page_rows;
                $config['cur_page'] = $page;
                $config['next_link'] = '>';
                $config['prev_link'] = '<';
                $config["uri_segment"] = 4;
                $this->pagination->initialize($config);

                $this->outputData['pagination'] = $this->pagination->create_links(false, 'recruitment');

                if ($this->session->userdata("project_" . $projectID)) {
                    $array = $this->session->userdata("project_" . $projectID);
                    $where_in = array();
                    foreach ($this->session->userdata("project_" . $projectID) as $value) {
                        $where_in[] = $value['dev_id'];
                    }
                    $conditions = array('projects.id' => $projectID, 'bids.is_deleted' => 0);
                    $this->outputData['listUserShortlist'] = $this->skills_model->getUsersShortlist($conditions, $where_in);
                }
                //var_dump($project);
                //var_dump($this->outputData['listBid']->result()); die;
                $this->load->view("project/viewProjectAfterCreate",$this->outputData);
            }else{
                redirect('info');
            }


        }else{
            // redirect
            redirect("home");
        }
        
    }

    function viewJobWhenUnregister(){
        $this->load->helper("projectcases");
        $this->load->helper("transaction");
        if($this->loggedInUser || empty($this->uri->segment(3,'0')) || is_numeric($this->uri->segment(3,'0'))== false ){
            $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('You can not access to this page')));
            redirect("info");
        }else{
            $project_id = $this->uri->segment(3,'0');
            $conditions = array('projects.id' => $project_id);
            $result = $this->skills_model->getProjects($conditions);
            if($result -> num_rows() == 0){
                //Notification message
                $this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', $this->lang->line('project_not_available')));
                redirect('info');
            }
                $this->outputData['projects'] = $result->row();
                $creatorInfo = getUserInfo($result->row()->creator_id);

                if($creatorInfo != '')
                    $this->outputData['creatorInfo'] = $creatorInfo;
                $conditions_skill = array('categories.is_deleted' => 0);
                $fields = array('categories.category_name','categories.id');
                $this->outputData['list_skills'] = $this->skills_model->getCategories($conditions_skill,$fields);

                $limit = array(4,0);
                $same_pr = $this->user_model->getSameProject($result->row()->project_categories,$project_id,$limit);
                if($same_pr->num_rows() > 0)
                    $this->outputData['same_projects'] = $same_pr;

        }
        $this->load->view("project/viewJobWhenUnregister",$this->outputData);
    }

    function shortlist(){
        $project_id = $this->input->post("pr_id",TRUE);
        $user_id = $this->input->post("user_id",TRUE);
        $flag = $this->input->post("flag",TRUE);
        if($flag == 1){
            if(isset($project_id) && isset($user_id)){
                if($this->session->userdata("project_".$project_id)){
                    // nếu đã có session thì thêm vàos
                    $array = $this->session->userdata("project_".$project_id);
                    $array[] = array(
                         "dev_id" => $user_id,
                     );
                    $this->session->set_userdata("project_".$project_id,$array);
                }else{
                    // nếu chưa có session thì tạo
                    $array = array();
                    $array[] = array("dev_id" => $user_id);
                    //$array[] = $array;
                    $this->session->set_userdata("project_".$project_id,$array);
                }
                echo json_encode(array(
                    "status"    => "success",
                    "msg"       => "Được chọn vào shortlist",
                    'user_id'   =>  $user_id
                ));
            }
        }else{
            if(isset($project_id) && isset($user_id)){
                //print_r("Delete -> project_id : ".$project_id." | user_id : ".$user_id);exit;
                if($this->session->userdata("project_".$project_id)){
                    // nếu đã có session thì thêm vàos
                    $array = $this->session->userdata("project_".$project_id);
                    foreach ($array as $key => $value) {
                        if($value['dev_id'] == $user_id){
                            unset($array[$key]);
                            $array = array_values($array);
                        }
                    }

                    $this->session->set_userdata("project_".$project_id,$array);
                    echo json_encode(array(
                        "status"    => "success",
                        "msg"       => "Đã xóa khỏi shortlist",
                    ));
                }
            }
        }
        

    }
    function ajaxCancelProject(){
        $project_id = $this->input->post('project_id',TRUE);
        $status = $this->input->post('status',TRUE);

        if($project_id){
            $condition = array('project_status' => $status);
            $this->skills_model->updateProjects($project_id,$condition);
            echo json_encode(array('status' => 'success','data' => $status));
        }else{
            echo json_encode(array('status' => 'error','data' => $status));
        }
    }
    function updateProject(){
        //print_r($_POST);exit;
        $project_id = $this->input->post('project_id',TRUE);
        $list_id = $this->input->post('list_id',TRUE);
        $description = $this->input->post('description',TRUE);
        $name = $this->input->post('name',TRUE);
        if($project_id == "" || $list_id == "" || $description == "" || $name == ""){
            echo json_encode(array('status' => 'error'));exit;
        }else{
            $conditions = array('project_categories' => $list_id,'description' => $description,'project_name' => $name);
            $this->skills_model->updateProjects($project_id,$conditions);
            $data = array(
                'name' => $name,
                'list_id' => getCategoryLinks($list_id),
                'description' => $description
            );
            echo json_encode(array('status' => 'success','data' => $data));exit;
        }
    }

    function show_all_tab(){
        
    }

    function show_shortlist_tab(){
        // load helper
        $this->load->helper("bids");
        $this->load->helper("projectcases");
        // load lang
        $this->lang->load('enduser/viewProject', $this->config->item('language_code'));
        $this->lang->load('enduser/createBids', $this->config->item('language_code'));

        if($this->uri->segment(3)){
            $projectID = $this->uri->segment(3,'0');
            $this->outputData['project_id'] = $projectID;
            if($this->session->userdata("project_".$projectID)){

                $array = $this->session->userdata("project_".$projectID);
                $where_in = array();
                foreach ($this->session->userdata("project_".$projectID) as $value) {
                   $where_in[] = $value['dev_id'];
                }
                $conditions = array('projects.id' => $projectID,'bids.is_deleted' => 0);
                //print_r("projectid : " .$this->outputData['project_id']);exit;
                $this->outputData['listUserShortlist'] = $this->skills_model->getUsersShortlist($conditions,$where_in);
            }
            
            // echo "<pre>";
            // print_r($this->outputData['listBid']->result());
            // echo "</pre>";
            
        $this->load->view("project/show_shortlist_tab",$this->outputData);  
        }else{
            // redirect
        }
        
    }
    function repostProject(){
        $this->lang->load('enduser/common',$this->config->item('language_code'));
        $project_id = $this->input->post('project_id',TRUE);
        $time = $this->input->post('time',TRUE);
        $day = $this->input->post('day',TRUE);
        if($project_id){
            //$total = $time + 604800;
            $total = $time + ($day * 86400);
            if( ($time - time()) <= 86400) {
                $condition = array('enddate' => $total);
                $this->skills_model->updateProjects($project_id, $condition);
                echo json_encode(array('status' => 'success', 'messages' => $this->lang->line('Extend success'),'data' => $day.' days'));
                exit;
            }else {
                echo json_encode(array('status' => 'error', 'messages' => $this->lang->line('Project not extend')));
                exit;
            }
        }else{
            echo json_encode(array('status' => 'error','messages' => $this->lang->line('Extend fail')));exit;
        }
    }
    function editProject()
    {
        $this->load->library('form_validation');
        $this->load->library('upload');
        $this->load->library('images');
        //Load Form Helper
        $this->load->helper('form');
        $this->load->helper('file');
        $this->load->helper("bids_helper");
        $project_id = $this->uri->segment('3', 0);
        //echo $project_id;exit;
        if ($project_id) {
            $condition = array('projects.id' => $project_id);
            $this->outputData['projectDetail'] = $this->skills_model->getProjects($condition);
            if($this->outputData['projectDetail']->row()->creator_id == $this->loggedInUser->id){
            $condition_group = array('groups.is_deleted' => 0);
            $this->outputData['listGroup'] = $this->skills_model->getGroups($condition_group);
            $condition_categories = array('categories.is_deleted' => 0);
            $fields_categories = array('categories.category_name', 'categories.group_id', 'categories.id');
            $this->outputData['listCategories'] = $this->skills_model->getCategories($condition_categories, $fields_categories);
            // load countries
            $this->outputData['countries'] = $this->skills_model->getCountries(NULL, NULL, NULL, array('0' => 30));
                if ($this->input->post('createProject')) {
                    // Puhal Changes Start Following validations are to verify the post of Email address and Phone number (Sep 17 Issue 1)	-------------------------------------------

                    $this->form_validation->set_rules('project_name', 'lang:project_name_validation', 'required|trim|min_length[5]|xss_clean|alpha_space');
                    $this->form_validation->set_rules('group_id', 'group', 'required|trim|xss_clean');
                    $this->form_validation->set_rules('parent', 'parent', 'required|trim|xss_clean');
                    $this->form_validation->set_rules('description', 'lang:description_validation', 'trim|xss_clean');
                    //$this->form_validation->set_rules('project_categories', 'lang:Project Skills', 'required');//|callback_check_number_categories
                    $this->form_validation->set_rules('budget', 'lang:budget', 'required|trim|xss_clean');

                    if($_FILES['attachment']['name'] != "")
                        $this->form_validation->set_rules('attachment', 'lang:attachment', 'callback_attachment_check_image_edit');

                    $this->form_validation->set_message('required', '%s ' . $this->lang->line('required'));
                    $this->form_validation->set_message('min_length', '%s ' . $this->lang->line('min_length'));
                    $this->form_validation->set_message('is_unique', '%s ' . $this->lang->line('is_unique'));

                    if ($this->form_validation->run() == TRUE) {
                        $insertData = array();
                        $insertData['project_name'] = $this->input->post('project_name', TRUE);
                        $insertData['description'] = $this->input->post('description', TRUE);


                        $array_categories = implode(',', $this->input->post('project_categories', TRUE));
                        $insertData['project_categories'] = $array_categories;

                        $insertData['group_id'] = $this->input->post('group_id', TRUE);
                        $insertData['project_type'] = $this->input->post('project_type', TRUE);

                        // add Freelancer Preferences
                        $insertData['is_private'] = $this->input->post('is_private', TRUE);
                        $insertData['provider_rated'] = $this->input->post('provider_rated', TRUE);
                        $insertData['locations'] = implode(',', $this->input->post('locations', TRUE));

                        //print_r($this->outputData['file']);exit;

                        if ((isset($this->outputData['file']))) {
                            //print_r($this->outputData['file']);exit;
                            $optionImage = array(
                                'upload-dir' => ROOT_PATH . '/files/project_attachment',
                                'thumbs' => array(
                                    array(
                                        'width' => 226,
                                        'height' => 195,
                                        'type' => 'absolute',
                                        'watermark' => false,
                                        'override' => true
                                    )));
                            $this->images->resizeImage($this->outputData['file']['file_name'], $optionImage);

                            $insertData['attachment_avatar'] = $this->outputData['file']['file_name'];

                            $this->images->remove($this->outputData['projectDetail']->row()->attachment_avatar,'/files/project_attachment',TRUE);

                        }
                        switch ($this->input->post('budget')) {
                            case '1':
                                $insertData['budget_min'] = 30;
                                $insertData['budget_max'] = 250;
                                break;
                            case '2':
                                $insertData['budget_min'] = 250;
                                $insertData['budget_max'] = 750;
                                break;
                            case '3':
                                $insertData['budget_min'] = 750;
                                $insertData['budget_max'] = 1500;
                                break;
                            case '4':
                                $insertData['budget_min'] = 1500;
                                $insertData['budget_max'] = 3000;
                                break;
                            case '5':
                                $insertData['budget_min'] = 3000;
                                $insertData['budget_max'] = 5000;
                                break;
                            case '6':
                                $insertData['budget_min'] = 5000;
                                break;
                            default:
                                $insertData['budget_min'] = $this->input->post('customize_budget_min');
                                $insertData['budget_max'] = $this->input->post('customize_budget_max');
                                break;
                        }
                        //print_r($insertData);exit;
                        $this->skills_model->updateProjects($project_id, $insertData);
                        redirect('project/viewProjectAfterCreate/' . $project_id);
                    }
                }
            }else{
                //$this->session->set_flashdata('flash_message', $this->common_model->flash_message('error', 'Bạn không có quyền vào trang này'));
                redirect('home');
            }
            $this->load->view('project/editProject', $this->outputData);
        }
    }

	function ajaxGetProject(){
        $id = $this->input->post('project_id');
        $project = $this->skills_model->getProjects(array('projects.id' => $id), 'projects.description')->row();

        echo json_encode($project); die;
    }

} //End  Project Class
/* End of file Project.php */
/* Location: ./app/controllers/Project.php */
?>